diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..6313b56c5 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..7c3fe4741 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,35 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +version: 2 +updates: + - package-ecosystem: "maven" + directory: "/p3c-pmd/" + schedule: + interval: "daily" + target-branch: "xenoamess_maintain_fork" + open-pull-requests-limit: 100 + - package-ecosystem: "gradle" + directory: "/idea-plugin/" + schedule: + interval: "daily" + target-branch: "xenoamess_maintain_fork" + open-pull-requests-limit: 100 + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "daily" + target-branch: "xenoamess_maintain_fork" + open-pull-requests-limit: 100 diff --git a/.github/workflows/auto-merge.yml b/.github/workflows/auto-merge.yml new file mode 100644 index 000000000..f912337ef --- /dev/null +++ b/.github/workflows/auto-merge.yml @@ -0,0 +1,14 @@ +name: auto-merge + +on: + pull_request: + +jobs: + auto-merge: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: ahmadnassri/action-dependabot-auto-merge@v2 + with: + target: minor + github-token: ${{ secrets.mytoken }} diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 000000000..1488a9d30 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,63 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +name: Java CI + +on: [ push ] + +jobs: + build: + runs-on: ${{ matrix.os }} + continue-on-error: ${{ matrix.experimental }} + strategy: + matrix: + os: [ windows-latest , ubuntu-latest , macos-latest ] + java: [ 17 ] + experimental: [ false ] + + steps: + - uses: actions/checkout@v5 + - uses: actions/cache@v4 + with: + path: ~/.m2 + key: ${{ runner.os }}-gradle-m2-${{ hashFiles('**/build.gradle') }} + restore-keys: | + ${{ runner.os }}-gradle- + - uses: actions/cache@v4 + with: + path: ~/.gradle/caches/ + key: ${{ runner.os }}-gradle-caches-${{ hashFiles('**/build.gradle') }} + restore-keys: | + ${{ runner.os }}-gradle- + - uses: actions/cache@v4 + with: + path: ~/.gradle/wrapper/ + key: ${{ runner.os }}-gradle-wrapper-${{ hashFiles('**/build.gradle') }} + restore-keys: | + ${{ runner.os }}-gradle- + - name: Set up JDK ${{ matrix.java }} + uses: actions/setup-java@v5 + with: + java-version: ${{ matrix.java }} + distribution: adopt + - name: Build Build Build! + run: | + cd ./p3c-pmd + chmod 777 ./mvnw + ./mvnw install -Penforce + cd ../ + cd ./idea-plugin + chmod 777 ./gradlew + ./gradlew buildPlugin -s diff --git a/.gitignore b/.gitignore index 08a3264a6..9cc9538ea 100644 --- a/.gitignore +++ b/.gitignore @@ -71,7 +71,6 @@ configuration/** # sass gitignore# .sass-cache -.idea # tcc_coverage coverage.ec @@ -82,7 +81,6 @@ config.client.* temp/ *.pid -*.orig hsf.configuration/ @@ -93,3 +91,6 @@ hsf.configuration/ *.instance out !/p3c-idea/src/main/kotlin/com/alibaba/smartfox/work/tools/aone/ui/AoneBranchView.kt + +#versions-maven-plugin +*.versionsBackup \ No newline at end of file diff --git a/.mvn/wrapper/MavenWrapperDownloader.java b/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 000000000..b901097f2 --- /dev/null +++ b/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,117 @@ +/* + * Copyright 2007-present the original author or authors. + * + * 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. + */ +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.6"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if(mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if(mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if(!outputFile.getParentFile().exists()) { + if(!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 000000000..2cc7d4a55 Binary files /dev/null and b/.mvn/wrapper/maven-wrapper.jar differ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 000000000..642d572ce --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/README.md b/README.md index 40f20c5f3..ba7f77a7a 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,52 @@ # P3C [![License](https://img.shields.io/badge/license-Apache%202-4EB1BA.svg)](https://www.apache.org/licenses/LICENSE-2.0.html) +[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=p3c-idea&metric=alert_status)](https://sonarcloud.io/dashboard?id=p3c-idea) +p3c-cmd -## Preface +[![idea plugin](https://sonarcloud.io/api/project_badges/measure?project=p3c-idea&metric=alert_status)](https://sonarcloud.io/dashboard?id=p3c-idea) +idea plugin(p3c-common) + +## Notice 声明 +This Third-party maintenance(TPM) here is forked from original [alibaba/p3c](https://github.com/alibaba/p3c) + +Follows Apache license described in [license](license.txt) + +Sources can be found https://github.com/XenoAmess/p3c + +Releases can be found at https://plugins.jetbrains.com/plugin/14109-alibaba-java-coding-guidelines-xenoamess-tpm- + +This TPM aims to help maintain alibaba/p3c, fix bugs, and add improvements, as the original developer is too busy to handle them. + +This TPM is NOT created, or maintained, or controlled by any alibaba employee, in other words it is a TPM, but not an official branch. + +TPM maintainer XenoAmess have no knowledge with eclipse plugin development. + +TPM maintainer XenoAmess suggest you only create pr for module idea-plugin and p3c-pmd, unless you really have a strong reason. + +## Features 特性 + +1. This TPM can always run on latest Jetbrains-idea release/EAP. + + 本第三方维护版会在任何 Jetbrains-idea release 或者EAP更新时保证可用。 + +2. This TPM will always use as latest dependencies as possible. + + 本第三方维护版会使用尽可能新的依赖版本。 + +3. This TPM implements a mechanism for configuring black-list/white-list for rules/classes + + 本第三方维护版实现有一套配置系统,可以对源码类/规则进行黑名单/白名单过滤。 + +4. This TPM does NOT fully obey p3c rules. + Especially for the rule who disable deprecated functions. + Maintainer XenoAmess will make sure they are usable, + but have no enough time to eliminate every deprecated functions. + + 本第三方维护版不完全遵循p3c,尤其是关于禁止使用deprecated函数的规则。 + 维护者XenoAmess会保证函数可用,但是没有充裕的时间保证消灭每一个deprecated函数。 + +## Preface 前言 > We are pleased to present Alibaba Java Coding Guidelines which consolidates the best programming practices over the years from Alibaba Group's technical teams. A vast number of Java programming teams impose demanding requirements on code quality across projects as we encourage reuse and better understanding of each other's programs. We have seen many programming problems in the past. For example, defective database table structures and index designs may cause software architecture flaws and performance risks. Another example is confusing code structures being difficult to maintain. Furthermore, vulnerable code without authentication is prone to hackers’ attacks. To address these kinds of problems, we developed this document for Java developers at Alibaba. For more information please refer the *Alibaba Java Coding Guidelines*: @@ -11,13 +55,13 @@ For more information please refer the *Alibaba Java Coding Guidelines*: - 《阿里巴巴Java开发手册》书籍版天猫官方店: *[阿里巴巴Java开发手册最新版](https://detail.tmall.com/item.htm?spm=a220m.1000858.1000725.1.4577601asIhzbW&id=628337143778&areaId=330100&user_id=1932014659&cat_id=2&is_b=1&rn=11a322ef70720cdf5e894001e4b48b55)* - 《码出高效》书籍版天猫官方店: *[码出高效:Java开发手册](https://detail.tmall.com/item.htm?spm=a230r.1.14.40.7dee7d6bwpO82U&id=575107529181&ns=1&abbucket=20)* -## Introduction +## Introduction 介绍 The project consists of 3 parts: - [PMD implementations](p3c-pmd) - [IntelliJ IDEA plugin](idea-plugin) - [Eclipse plugin](eclipse-plugin) -## Rules +## Rules 规则 Forty-nine rules are realized based on PMD, please refer the P3C-PMD documentation for more detailed information. Four rules are implemented within IDE plugins (IDEA and Eclipse) as follows: - ``[Mandatory]`` Using a deprecated class or method is prohibited. @@ -34,3 +78,10 @@ The project consists of 3 parts: 3. These two methods must be overridden if self-defined object is used as the key of Map. Note: String can be used as the key of Map since these two methods have been rewritten. +## Config Mechanism 配置机制 + +see + +[documents](idea-plugin/README.md) + +[说明](idea-plugin/README_cn.md) diff --git a/build.cmd b/build.cmd new file mode 100644 index 000000000..6a580c16c --- /dev/null +++ b/build.cmd @@ -0,0 +1,18 @@ +set JAVA_HOME=C:\jdk-21\ + +cd ./p3c-pmd +call ./mvnw clean install -Dmaven.javadoc.skip=false -e -X +cd ../ +cd ./idea-plugin + +set JAVA_HOME=C:\jdk-21\ + +cd ./p3c-common +call ../gradlew clean publishToMavenLocal +cd ../ + +cd ./p3c-idea +call ../gradlew clean publishToMavenLocal buildPlugin +cd ../ + +cd ../ diff --git a/deploy.cmd b/deploy.cmd new file mode 100644 index 000000000..3fa7b0652 --- /dev/null +++ b/deploy.cmd @@ -0,0 +1,19 @@ +set JAVA_HOME=C:\jdk-8\ + +cd ./p3c-pmd +call ./mvnw clean deploy -Dmaven.javadoc.skip=false -e -X -Psonatype-oss-release +cd ../ +cd ./idea-plugin + +set JAVA_HOME=C:\jdk-21\ + +cd ./p3c-common +rem call ../gradlew clean install sign uploadArchives -DossrhUsername="%ossrhUsername%" -DossrhPassword="%ossrhPassword%" +call ../gradlew publishToMavenLocal +cd ../ + +cd ./p3c-idea +call ../gradlew clean publishToMavenLocal buildPlugin +cd ../ + +cd ../ diff --git a/eclipse-plugin/.gitignore b/eclipse-plugin/.gitignore deleted file mode 100644 index 51836b5aa..000000000 --- a/eclipse-plugin/.gitignore +++ /dev/null @@ -1,97 +0,0 @@ -# Gradle -build -.gradle - -testdata/ -# Java gitignore # -.class -.log - -# Package Files # - -*.war -*.ear -*.gradle - -#hsf files -configuration - -# maven gitignore# -target/** - -.svn/ - -# intelliJ.gitignore # -.idea -*.iml -*.ipr -*.iws -*.bat - -# Eclipse git ignore# -*.pydevproject -.project -.metadata -bin/** -*/bin/** -tmp/** -tmp/**/* -configuration/** -*.tmp -*.bak -*.orig -*.swp -*~.nib -.classpath -.settings/ -.loadpath -.fileTable* -.cache - -# External tool builders -.externalToolBuilders/ - -# Locally stored "Eclipse launch configurations" -*.launch - -# CDT-specific -.cproject - -# PDT-specific -.buildpath - -#log -*.log -*.log.* - -# Windows Thumbs.db -*.db - -# OSX -.DS_Store - -# sass gitignore# -.sass-cache -.idea - -# tcc_coverage -coverage.ec - - - -config.client.* - -temp/ -*.pid -*.orig - -hsf.configuration/ - -# code coverage report -*.ec - -#hsf test -*.instance -**/target -.pmd -**/.pmd diff --git a/eclipse-plugin/README.md b/eclipse-plugin/README.md deleted file mode 100644 index 94b9dbcd1..000000000 --- a/eclipse-plugin/README.md +++ /dev/null @@ -1,31 +0,0 @@ -# Eclipse Plugin ---- -## Prepare -- Eclipse Juno+ -- maven3.+ -- JDK 1.7+ - -## Build -``` -mvn -U clean install -``` -## [中文使用手册](README_cn.md) -## Install -1. Help >> Install New Software -then enter this update site URL [https://p3c.alibaba.com/plugin/eclipse/update](https://p3c.alibaba.com/plugin/eclipse/update) - -![Install Plugin](doc/images/install.png) - -2. Follow the wizard, restart Eclipse to take effect after install success. - -## Use -1. Switch language - - ![Switch language](doc/images/eclipse_switch_language.png) - -2. Code Analyze - - ![Analyze](doc/images/eclipse_analyze.png) - - ![Analyze](doc/images/analyze_result.png) - diff --git a/eclipse-plugin/README_cn.md b/eclipse-plugin/README_cn.md deleted file mode 100644 index c133a3ee4..000000000 --- a/eclipse-plugin/README_cn.md +++ /dev/null @@ -1,63 +0,0 @@ -> 首先非常感谢大家对插件的支持与意见,Eclipse的功能相对来说比较简单,希望有更多的同学加入进来一起完善。 - -## 插件安装 -环境:JDK1.8,Eclipse4+。有同学遇到过这样的情况,安装插件重启后,发现没有对应的菜单项,从日志上也看不到相关的异常信息,最后把JDK从1.6升级到1.8解决问题。 - -Help -> Install New Software... - -![](https://gw.alicdn.com/tfscom/TB1LOyPifJNTKJjSspoXXc6mpXa.png) - -输入Update Site地址:https://p3c.alibaba.com/plugin/eclipse/update 回车,然后勾选Ali-CodeAnalysis,再一直点Next Next...按提示走下去就好。 然后就是提示重启了,安装完毕。 - -![](https://gw.alicdn.com/tfscom/TB1Ud5kifBNTKJjSszcXXbO2VXa.png) - -注意:有同学反映插件扫描会触发很多 "JPA Java Change Event Handler (Waiting)" 的任务,这个是Eclipse的一个[bug](https://bugs.eclipse.org/bugs/show_bug.cgi?id=387455),因为插件在扫描的时候会对文件进行标记,所以触发了JPA的任务。卸载JPA插件,或者尝试升级到最新版的Eclipse。附:[JPA project Change Event Handler问题解决](https://my.oschina.net/cimu/blog/278724) - - -## 插件使用 - -目前插件实现了开发手册中的53条规则,大部分基于PMD实现,其中有4条规则基于Eclipse实现,支持4条规则的QuickFix功能。 - - * 所有的覆写方法,必须加@Override注解, - * if/for/while/switch/do等保留字与左右括号之间都必须加空格, - * long或者Long初始赋值时,必须使用大写的L,不能是小写的l) - * Object的equals方法容易抛空指针异常,应使用常量或确定有值的对象来调用equals。 - -目前不支持代码实时检测,需要手动触发,希望更多的人加入进来一起把咱们的插件做得越来越好,尽量提升研发的使用体验。 - - -### 代码扫描 -可以通过右键菜单、Toolbar按钮两种方式手动触发代码检测。同时结果面板中可以对部分实现了QuickFix功能的规则进行快速修复。 - -#### 触发扫描 -在当前编辑的文件中点击右键,可以在弹出的菜单中触发对该文件的检测。 - -![](https://gw.alicdn.com/tfscom/TB1XGo8iPihSKJjy0FeXXbJtpXa.png) - - -在左侧的Project目录树种点击右键,可以触发对整个工程或者选择的某个目录、文件进行检测。 - -![](https://gw.alicdn.com/tfscom/TB18UsJi2NZWeJjSZFpXXXjBFXa.png) - - -也可以通过Toolbar中的按钮来触发检测,目前Toolbar的按钮触发的检测范围与您IDE当时的焦点有关,如当前编辑的文件或者是Project目录树选中的项,是不是感觉与右键菜单的检测范围类似呢。 - - ![](https://gw.alicdn.com/tfscom/TB1vt1oifBNTKJjSszcXXbO2VXa.png) - - -#### 扫描结果 -简洁的结果面板,按规则等级分类,等级->规则->文件->违规项。同时还提供一个查看规则详情的界面。 - -清除结果标记更方便,支持上面提到的4条规则QuickFix。 - -![](https://gw.alicdn.com/tfscom/TB1_uFJi6ihSKJjy0FlXXadEXXa.png) - -#### 查看所有规则 -![](https://gw.alicdn.com/tfscom/TB1UNTnmYsTMeJjSszhXXcGCFXa.png) -![](https://gw.alicdn.com/tfscom/TB1_rf7sOAKL1JjSZFoXXagCFXa.png) - -#### 国际化 - -![](https://gw.alicdn.com/tfscom/TB1KsyYsiFTMKJjSZFAXXckJpXa.png) - -![](https://gw.alicdn.com/tfscom/TB19bzdm3oQMeJjy1XaXXcSsFXa.png) diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/build.properties b/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/build.properties deleted file mode 100644 index 1dceaa621..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/build.properties +++ /dev/null @@ -1,7 +0,0 @@ -bin.includes = feature.xml,\ - feature.properties,\ - smartfox.png -src.includes = build.properties,\ - feature.properties,\ - feature.xml,\ - smartfox.png diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/feature.properties b/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/feature.properties deleted file mode 100644 index 5bd3a3136..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/feature.properties +++ /dev/null @@ -1,26 +0,0 @@ -feature.label = Ali-CodeAnalysis -feature.provider_name = Alibaba -feature.update_site_name = Alibaba IDE Portal - -description.text = Alibaba Java Coding Guidelines -description.url = https://github.com/alibaba/p3c - -copyright.text =\ -Copyright 2017 Alibaba Java Coding Guidelines - -license.url = https://github.com/alibaba/p3c -license.text =\ - Copyright 1999-2017 Alibaba Group. \n\ - \n\ - Licensed under the Apache License, Version 2.0 (the "License"); \n\ - you may not use this file except in compliance with the License. \n\ - You may obtain a copy of the License at \n\ - \n\ - http://www.apache.org/licenses/LICENSE-2.0 \n\ - \n\ - Unless required by applicable law or agreed to in writing, software \n\ - distributed under the License is distributed on an "AS IS" BASIS, \n\ - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \n\ - See the License for the specific language governing permissions and \n\ - limitations under the License. \n\ - diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/feature.xml b/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/feature.xml deleted file mode 100644 index ba5102e3e..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/feature.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - Alibaba Java Coding Guidelines - - - - %copyright.text - - - - %license.text - - - - - - - - - - - - - - - - - - - - - - - diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/pom.xml b/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/pom.xml deleted file mode 100644 index 4fcddb1b1..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/pom.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - 4.0.0 - - com.alibaba.smartfox.eclipse - smartfox-eclipse - 2.0.1-SNAPSHOT - - com.alibaba.smartfox.eclipse.feature - eclipse-feature - 2017 - diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/smartfox.png b/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/smartfox.png deleted file mode 100644 index 75a2c1bb3..000000000 Binary files a/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/smartfox.png and /dev/null differ 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 deleted file mode 100644 index 0732ec54b..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/META-INF/MANIFEST.MF +++ /dev/null @@ -1,59 +0,0 @@ -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: 2.0.1.qualifier -Bundle-Activator: com.alibaba.smartfox.eclipse.SmartfoxActivator -Bundle-Vendor: Alibaba -Require-Bundle: org.eclipse.ui, - org.eclipse.core.runtime, - org.eclipse.jdt.core, - org.eclipse.ui.ide, - org.eclipse.ui.views, - org.eclipse.core.resources, - org.eclipse.jface.text, - org.eclipse.ui.workbench.texteditor, - org.eclipse.ltk.core.refactoring, - org.eclipse.jdt.ui, - org.eclipse.core.filebuffers, - org.eclipse.equinox.p2.core, - org.eclipse.equinox.p2.engine, - org.eclipse.equinox.p2.operations, - org.eclipse.equinox.p2.metadata.repository, - org.eclipse.equinox.p2.ui, - org.eclipse.equinox.p2.metadata -Bundle-RequiredExecutionEnvironment: JavaSE-1.8 -Bundle-ActivationPolicy: lazy -Bundle-ClassPath: target/lib/antlr-runtime.jar, - target/lib/antlr4-runtime.jar, - target/lib/asm.jar, - target/lib/commons-io.jar, - target/lib/commons-lang3.jar, - target/lib/gson.jar, - target/lib/javacc.jar, - target/lib/jaxen.jar, - target/lib/jcommander.jar, - target/lib/log4j.jar, - target/lib/pmd-core.jar, - target/lib/pmd-java.jar, - target/lib/pmd-javascript.jar, - target/lib/pmd-vm.jar, - target/lib/rhino.jar, - target/lib/saxon-dom.jar, - target/lib/saxon.jar, - target/lib/p3c-pmd.jar, - target/lib/kotlin-stdlib.jar, - target/lib/statistics-client.jar, - target/lib/guava.jar, - target/classes/, - . -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, - com.alibaba.smartfox.eclipse.ui.pmd, - com.alibaba.smartfox.eclipse.util diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/build.properties b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/build.properties deleted file mode 100644 index b305b3680..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/build.properties +++ /dev/null @@ -1,14 +0,0 @@ -bin.includes = .,\ - META-INF/,\ - plugin.xml,\ - icons/,\ - target/lib/ -src.includes = icons/,\ - META-INF/,\ - plugin.xml,\ - messages.properties,\ - target/lib/,\ - src/main/kotlin,\ - pom.xml -source.. = src/main/java/,src/main/resources -output.. = target/classes/ diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/actions/clear.gif b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/actions/clear.gif deleted file mode 100644 index 2cd9c5444..000000000 Binary files a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/actions/clear.gif and /dev/null differ diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/actions/clear.png b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/actions/clear.png deleted file mode 100644 index 8c5c1a001..000000000 Binary files a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/actions/clear.png and /dev/null differ diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/actions/quickfixBulb.png b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/actions/quickfixBulb.png deleted file mode 100644 index ecc6c160a..000000000 Binary files a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/actions/quickfixBulb.png and /dev/null differ diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/actions/rules.png b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/actions/rules.png deleted file mode 100644 index 9990f5f1a..000000000 Binary files a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/actions/rules.png and /dev/null differ diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/ali-ide-run.png b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/ali-ide-run.png deleted file mode 100644 index 754649e9c..000000000 Binary files a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/ali-ide-run.png and /dev/null differ diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/language.png b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/language.png deleted file mode 100644 index b26745460..000000000 Binary files a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/language.png and /dev/null differ diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/blocker.gif b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/blocker.gif deleted file mode 100644 index 2ff667899..000000000 Binary files a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/blocker.gif and /dev/null differ diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/class_obj.png b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/class_obj.png deleted file mode 100644 index bc915da44..000000000 Binary files a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/class_obj.png and /dev/null differ diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/critical.gif b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/critical.gif deleted file mode 100644 index a01bb24b7..000000000 Binary files a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/critical.gif and /dev/null differ diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/major.png b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/major.png deleted file mode 100644 index 87adef9f9..000000000 Binary files a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/major.png and /dev/null differ diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/smartfox_logo.png b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/smartfox_logo.png deleted file mode 100644 index 4a56fac4a..000000000 Binary files a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/smartfox_logo.png and /dev/null differ diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/plugin.xml b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/plugin.xml deleted file mode 100644 index 358581b33..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/plugin.xml +++ /dev/null @@ -1,153 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/pom.xml b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/pom.xml deleted file mode 100644 index 2843498f3..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/pom.xml +++ /dev/null @@ -1,124 +0,0 @@ - - - 4.0.0 - - com.alibaba.smartfox.eclipse - smartfox-eclipse - 2.0.1-SNAPSHOT - - com.alibaba.smartfox.eclipse.plugin - eclipse-plugin - 2017 - - false - - - - log4j - log4j - 1.2.17 - - - com.alibaba.p3c - p3c-pmd - 2.0.1 - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - - - com.google.guava - guava - 20.0 - - - - src/main/kotlin - - - org.jetbrains.kotlin - kotlin-maven-plugin - ${kotlin.version} - - - - compile - compile - - compile - - - - - test-compile - test-compile - - test-compile - - - - - - org.apache.maven.plugins - maven-dependency-plugin - 3.1.1 - - true - false - ${project.build.directory}/lib - - p2.eclipse-plugin,apex - com.alibaba.smartfox.eclipse.plugin - - false - - - - get-dependencies - process-sources - - copy-dependencies - - - - - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - - org.apache.maven.plugins - - - maven-dependency-plugin - - [0,) - - copy-dependencies - - - - - - - - - - - - - - diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/QuickFix.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/QuickFix.kt deleted file mode 100644 index 51e02aa52..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/QuickFix.kt +++ /dev/null @@ -1,119 +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.smartfox.eclipse - -import com.alibaba.p3c.pmd.lang.java.rule.constant.UpperEllRule -import com.alibaba.p3c.pmd.lang.java.rule.oop.EqualsAvoidNullRule -import com.alibaba.smartfox.eclipse.ui.InspectionResults -import com.alibaba.smartfox.eclipse.util.getRule -import com.google.common.io.Files -import org.eclipse.core.resources.IFile -import org.eclipse.core.resources.IMarker -import org.eclipse.core.runtime.NullProgressMonitor -import org.eclipse.ltk.core.refactoring.TextFileChange -import org.eclipse.text.edits.ReplaceEdit -import org.eclipse.ui.IMarkerResolution -import org.eclipse.ui.IMarkerResolutionGenerator -import java.nio.charset.Charset - -/** - * - * - * @author caikang - * @date 2017/06/14 - */ -class QuickFixGenerator : IMarkerResolutionGenerator { - override fun getResolutions(marker: IMarker): Array { - if (!marker.exists()) { - return emptyArray() - } - val rule = marker.getRule() - val quickFix = quickFixes[rule.name] ?: return emptyArray() - return arrayOf(quickFix) - } - - companion object { - val quickFixes = mapOf(UpperEllRule::class.java.simpleName to UpperEllQuickFix, - EqualsAvoidNullRule::class.java.simpleName to EqualsAvoidNullQuickFix) - } -} - -interface RunWithoutViewRefresh : IMarkerResolution { - fun run(marker: IMarker, refresh: Boolean) - - override fun run(marker: IMarker) { - run(marker, true) - } -} - -abstract class BaseQuickFix : RunWithoutViewRefresh { - override fun run(marker: IMarker, refresh: Boolean) { - if (!marker.exists()) { - return - } - val file = marker.resource as IFile - doRun(marker, file) - marker.delete() - if (refresh) { - InspectionResults.removeMarker(marker) - } - } - - abstract fun doRun(marker: IMarker, file: IFile) -} - -object UpperEllQuickFix : BaseQuickFix() { - override fun doRun(marker: IMarker, file: IFile) { - val offset = marker.getAttribute(IMarker.CHAR_START, 0) - val end = marker.getAttribute(IMarker.CHAR_END, 0) - val content = Files.toString(file.rawLocation.toFile(), Charset.forName(file.charset)) - val replaceString = content.substring(offset, end + 1).replace("l", "L") - val edit = ReplaceEdit(offset, replaceString.length, replaceString) - val change = TextFileChange("", file) - change.edit = edit - change.perform(NullProgressMonitor()) - } - - override fun getLabel(): String { - return "Replace 'l' to 'L'." - } - -} - -object EqualsAvoidNullQuickFix : BaseQuickFix() { - val equalsName = ".equals(" - - override fun doRun(marker: IMarker, file: IFile) { - val offset = marker.getAttribute(IMarker.CHAR_START, 0) - val end = marker.getAttribute(IMarker.CHAR_END, 0) - val content = Files.toString(file.rawLocation.toFile(), Charset.forName(file.charset)) - val string = content.substring(offset, end) - val list = string.split(equalsName).filterNotNull() - if (list.size != 2) { - return - } - val replace = "${list[1].substringBeforeLast(')')}$equalsName${list[0]})" - val edit = ReplaceEdit(offset, string.length, replace) - val change = TextFileChange("", file) - change.edit = edit - change.perform(NullProgressMonitor()) - } - - override fun getLabel(): String { - return "Flip equals." - } - -} \ No newline at end of file diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/SmartfoxActivator.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/SmartfoxActivator.kt deleted file mode 100644 index 4895aa0b6..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/SmartfoxActivator.kt +++ /dev/null @@ -1,141 +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.smartfox.eclipse - -import com.alibaba.p3c.pmd.I18nResources -import net.sourceforge.pmd.Rule -import net.sourceforge.pmd.RuleSetFactory -import net.sourceforge.pmd.RuleSets -import org.apache.log4j.Logger -import org.eclipse.core.runtime.IStatus -import org.eclipse.core.runtime.Status -import org.eclipse.jface.dialogs.MessageDialog -import org.eclipse.jface.resource.ImageDescriptor -import org.eclipse.swt.graphics.Image -import org.eclipse.swt.widgets.Display -import org.eclipse.ui.plugin.AbstractUIPlugin -import org.osgi.framework.BundleContext -import java.util.Locale - -/** - * @author caikang - * @date 2017/06/14 - */ -class SmartfoxActivator : AbstractUIPlugin() { - - init { - aDefault = this - } - - private val logger = Logger.getLogger(javaClass)!! - lateinit var ruleSets: RuleSets - private val localeKey = "p3c.locale" - - lateinit var ruleMap: Map - - @Throws(Exception::class) override fun start(context: BundleContext) { - super.start(context) - I18nResources.changeLanguage(locale) - ruleSets = createRuleSets() - ruleMap = ruleSets.allRules.associateBy { - it.name - } - } - - @Throws(Exception::class) override fun stop(context: BundleContext?) { - aDefault = null - super.stop(context) - } - - - fun getImage(key: String, iconPath: String = key): Image { - val registry = imageRegistry - var image: Image? = registry.get(key) - if (image == null) { - val descriptor = getImageDescriptor(iconPath) - registry.put(key, descriptor) - image = registry.get(key) - } - - return image!! - } - - val locale: String - get() { - val language = preferenceStore.getString(localeKey) - if (language.isNullOrBlank()) { - val lang = Locale.getDefault().language - return if (lang != Locale.ENGLISH.language && lang != Locale.CHINESE.language) { - Locale.ENGLISH.language - } else Locale.getDefault().language - } - - return language - } - - fun toggleLocale() { - val lang = if (Locale.ENGLISH.language == locale) Locale.CHINESE.language else Locale.ENGLISH.language - preferenceStore.setValue(localeKey, lang) - } - - fun getRule(rule: String): Rule { - return ruleMap[rule]!! - } - - fun showError(message: String, t: Throwable) { - logError(message, t) - Display.getDefault().syncExec { - MessageDialog.openError(Display.getCurrent().activeShell, "错误", message + "\n" + t.toString()) - } - } - - fun logError(message: String, t: Throwable) { - log.log(Status(IStatus.ERROR, bundle.symbolicName, 0, message + t.message, t)) - logger.error(message, t) - } - - fun logError(status: IStatus) { - log.log(status) - logger.error(status.message, status.exception) - } - - fun logInformation(message: String) { - log.log(Status(IStatus.INFO, bundle.symbolicName, 0, message, null)) - } - - fun logWarn(message: String) { - log.log(Status(IStatus.WARNING, bundle.symbolicName, 0, message, null)) - } - - companion object { - // The plug-in ID - val PLUGIN_ID = "com.alibaba.smartfox.eclipse.plugin" - - var aDefault: SmartfoxActivator? = null - private set - - val instance: SmartfoxActivator get() = aDefault!! - - fun getImageDescriptor(path: String): ImageDescriptor { - return AbstractUIPlugin.imageDescriptorFromPlugin(PLUGIN_ID, path) - } - - fun createRuleSets(): RuleSets { - val ruleSetFactory = RuleSetFactory() - return ruleSetFactory.createRuleSets("java-ali-pmd,vm-ali-other") - } - } -} diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/handler/CodeAnalysisHandler.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/handler/CodeAnalysisHandler.kt deleted file mode 100644 index f2730a2fd..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/handler/CodeAnalysisHandler.kt +++ /dev/null @@ -1,105 +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.smartfox.eclipse.handler - -import com.alibaba.smartfox.eclipse.job.CodeAnalysis.processResources -import com.alibaba.smartfox.eclipse.message.P3cBundle -import com.google.common.collect.Sets -import org.apache.log4j.Logger -import org.eclipse.core.commands.AbstractHandler -import org.eclipse.core.commands.ExecutionEvent -import org.eclipse.core.commands.ExecutionException -import org.eclipse.core.resources.IFile -import org.eclipse.core.resources.IResource -import org.eclipse.core.resources.IResourceVisitor -import org.eclipse.core.runtime.IAdaptable -import org.eclipse.jface.viewers.IStructuredSelection -import org.eclipse.ui.IFileEditorInput -import org.eclipse.ui.IWorkingSet -import org.eclipse.ui.commands.IElementUpdater -import org.eclipse.ui.handlers.HandlerUtil -import org.eclipse.ui.menus.UIElement -import org.eclipse.ui.part.EditorPart -import org.eclipse.ui.part.ViewPart - -/** - * @author caikang - * @date 2016/12/27 - */ -open class CodeAnalysisHandler : AbstractHandler(), IElementUpdater { - override fun updateElement(element: UIElement, parameters: MutableMap?) { - val text = P3cBundle.getMessage("com.alibaba.smartfox.eclipse.handler.CodeAnalysisHandler") - element.setText(text) - element.setTooltip(text) - } - - @Throws(ExecutionException::class) - override fun execute(executionEvent: ExecutionEvent): Any? { - val selection = HandlerUtil.getCurrentSelectionChecked(executionEvent) - val part = HandlerUtil.getActivePart(executionEvent) - if (part is ViewPart) { - if (selection is IStructuredSelection) { - processForMutiFiles(selection) - } - } else if (part is EditorPart) { - val editorInput = HandlerUtil.getActiveEditorInput(executionEvent) - if (editorInput is IFileEditorInput) { - processResources(setOf(editorInput.file)) - } - } - return null - } - - private fun processForMutiFiles(selection: IStructuredSelection) { - val resources = getSelectionResources(selection) - processResources(resources) - } - - private fun getSelectionResources(selection: IStructuredSelection): MutableSet { - val resources = mutableSetOf() - selection.toList().forEach { - when (it) { - is IWorkingSet -> it.elements.mapTo(resources) { it.getAdapter(IResource::class.java) as IResource } - is IAdaptable -> { - val file = it.getAdapter(IResource::class.java) as? IResource ?: return@forEach - resources.add(file) - } - else -> log.warn("The selected object is not adaptable : ${it.toString()}") - } - } - return resources - } - - - companion object { - private val log = Logger.getLogger(CodeAnalysisHandler::class.java) - } -} - -class FileCollectVisitor : IResourceVisitor { - val fileSet = Sets.newLinkedHashSet()!! - - override fun visit(resource: IResource?): Boolean { - if (resource == null) { - return false - } - val file = resource.getAdapter(IFile::class.java) as? IFile ?: return true - if (file.exists() && (file.fileExtension == "java" || file.fileExtension == "vm")) { - fileSet.add(file) - } - return false - } -} \ No newline at end of file diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/handler/SwitchLanguageHandler.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/handler/SwitchLanguageHandler.kt deleted file mode 100644 index e12ba128f..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/handler/SwitchLanguageHandler.kt +++ /dev/null @@ -1,52 +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.smartfox.eclipse.handler - -import com.alibaba.smartfox.eclipse.SmartfoxActivator -import com.alibaba.smartfox.eclipse.message.P3cBundle -import org.eclipse.core.commands.AbstractHandler -import org.eclipse.core.commands.ExecutionEvent -import org.eclipse.jface.dialogs.MessageDialog -import org.eclipse.ui.PlatformUI -import org.eclipse.ui.commands.IElementUpdater -import org.eclipse.ui.menus.UIElement - -/** - * - * - * @author caikang - * @date 2017/06/21 - */ -class SwitchLanguageHandler : AbstractHandler(), IElementUpdater { - val handlerKey = "com.alibaba.smartfox.eclipse.handler.SwitchLanguageHandler" - val textKey = "$handlerKey.text.cur_" - - override fun execute(executionEvent: ExecutionEvent): Any? { - SmartfoxActivator.instance.toggleLocale() - if (!MessageDialog.openConfirm(null, "Tips", - P3cBundle.getMessage("$handlerKey.success.${SmartfoxActivator.instance.locale}"))) { - return null - } - PlatformUI.getWorkbench().restart() - return null - } - - override fun updateElement(element: UIElement, parameters: MutableMap?) { - val text = P3cBundle.getMessage("$textKey${SmartfoxActivator.instance.locale}") - element.setText(text) - element.setTooltip(text) - } -} \ No newline at end of file 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 deleted file mode 100644 index 166c8e37e..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/job/CodeAnalysis.kt +++ /dev/null @@ -1,133 +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.smartfox.eclipse.job - -import com.alibaba.p3c.pmd.lang.java.util.GeneratedCodeUtils -import com.alibaba.smartfox.eclipse.SmartfoxActivator -import com.alibaba.smartfox.eclipse.handler.CodeAnalysisHandler -import com.alibaba.smartfox.eclipse.handler.FileCollectVisitor -import com.alibaba.smartfox.eclipse.ui.InspectionResultView -import com.alibaba.smartfox.eclipse.ui.InspectionResults -import com.alibaba.smartfox.eclipse.ui.MarkerViolation -import com.alibaba.smartfox.eclipse.util.MarkerUtil -import com.google.common.io.Files -import net.sourceforge.pmd.PMDConfiguration -import net.sourceforge.pmd.PMDException -import net.sourceforge.pmd.Report -import net.sourceforge.pmd.RuleContext -import net.sourceforge.pmd.RuleViolation -import net.sourceforge.pmd.SourceCodeProcessor -import org.apache.log4j.Logger -import org.eclipse.core.resources.IFile -import org.eclipse.core.resources.IResource -import org.eclipse.core.runtime.IProgressMonitor -import org.eclipse.core.runtime.IStatus -import org.eclipse.core.runtime.Status -import org.eclipse.core.runtime.SubMonitor -import org.eclipse.core.runtime.jobs.Job -import java.io.IOException -import java.io.StringReader -import java.nio.charset.Charset - -/** - * - * - * @author caikang - * @date 2017/06/14 - */ -object CodeAnalysis { - private val log = Logger.getLogger(CodeAnalysisHandler::class.java) - - fun processResources(resources: Set) { - InspectionResultView.activeViews() - val job = object : Job("P3C Code Analysis") { - override fun run(monitor: IProgressMonitor): IStatus { - val fileVisitor = FileCollectVisitor() - monitor.setTaskName("Collect files") - resources.forEach { - if (monitor.isCanceled) { - return@run Status.CANCEL_STATUS - } - if (it.isAccessible) { - it.accept(fileVisitor) - } - } - if (monitor.isCanceled) { - return Status.CANCEL_STATUS - } - val subMonitor = SubMonitor.convert(monitor, "Analysis files", fileVisitor.fileSet.size) - monitor.setTaskName("Analysis files") - fileVisitor.fileSet.forEach { iFile -> - if (monitor.isCanceled) { - return@run Status.CANCEL_STATUS - } - MarkerUtil.removeAllMarkers(iFile) - monitor.subTask(iFile.fullPath.toPortableString()) - val markers = processFileToMakers(iFile, monitor) - subMonitor.newChild(1) - InspectionResults.updateFileViolations(iFile, markers) - } - return Status.OK_STATUS - } - } - job.apply { - isUser = true - isSystem = false - priority = Job.INTERACTIVE - rule = P3cMutex - schedule() - } - } - - fun processFileToMakers(file: IFile, monitor: IProgressMonitor): List { - file.refreshLocal(IResource.DEPTH_ZERO, monitor) - val ruleViolations = processFile(file) - - MarkerUtil.removeAllMarkers(file) - return ruleViolations.map { - MarkerViolation(MarkerUtil.addMarker(file, it), it) - } - } - - private fun processFile(file: IFile): List { - val configuration = PMDConfiguration() - configuration.setSourceEncoding(file.charset ?: Charsets.UTF_8.name()) - configuration.inputPaths = file.fullPath.toPortableString() - val ctx = RuleContext() - ctx.setAttribute("eclipseFile", file) - val niceFileName = configuration.inputPaths - val report = Report.createReport(ctx, niceFileName) - SmartfoxActivator.instance.ruleSets.start(ctx) - val processor = SourceCodeProcessor(configuration) - try { - ctx.languageVersion = null - val content = Files.toString(file.rawLocation.toFile(), Charset.forName(file.charset)) - if (!GeneratedCodeUtils.isGenerated(content)) { - processor.processSourceCode(StringReader(content), SmartfoxActivator.instance.ruleSets, ctx) - } - } catch (pmde: PMDException) { - 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) - } catch (re: RuntimeException) { - log.error("RuntimeException while processing file: " + niceFileName, re) - } finally { - SmartfoxActivator.instance.ruleSets.end(ctx) - } - return report.toList() - } -} diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/RulePriority.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/RulePriority.kt deleted file mode 100644 index 260ffc15c..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/RulePriority.kt +++ /dev/null @@ -1,35 +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.smartfox.eclipse.pmd - -enum class RulePriority(val priority: Int, val title: String) { - - Blocker(1, "Blocker"), Critical(2, "Critical"), Major(3, "Major"); - - override fun toString(): String { - return title - } - - companion object { - fun valueOf(priority: Int): RulePriority { - try { - return RulePriority.values()[priority - 1] - } catch (e: ArrayIndexOutOfBoundsException) { - return Major - } - } - } -} 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 deleted file mode 100644 index cdae0301b..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/AbstractEclipseRule.kt +++ /dev/null @@ -1,185 +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.smartfox.eclipse.pmd.rule - -import com.alibaba.smartfox.eclipse.message.P3cBundle -import net.sourceforge.pmd.Rule -import net.sourceforge.pmd.RuleContext -import net.sourceforge.pmd.RuleViolation -import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit -import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule -import org.eclipse.core.resources.IFile -import org.eclipse.core.runtime.NullProgressMonitor -import org.eclipse.jdt.core.ICompilationUnit -import org.eclipse.jdt.core.IProblemRequestor -import org.eclipse.jdt.core.JavaCore -import org.eclipse.jdt.core.JavaModelException -import org.eclipse.jdt.core.WorkingCopyOwner -import org.eclipse.jdt.core.compiler.IProblem -import org.eclipse.jdt.core.dom.ASTNode -import org.eclipse.jdt.core.dom.ASTVisitor -import org.eclipse.jdt.core.dom.CompilationUnit -import java.util.MissingResourceException - -/** - * @author caikang - * @date 2016/12/26 - */ -abstract class AbstractEclipseRule : AbstractJavaRule() { - - open fun getErrorMessage(): String { - return message - } - - override fun visit(node: ASTCompilationUnit, data: Any): Any? { - val result = super.visit(node, data) - val ruleContext = data as RuleContext - val file = ruleContext.getAttribute("eclipseFile") as? IFile ?: return result - val compilationUnit = JavaCore.createCompilationUnitFrom(file) ?: return data - try { - val requestor = object : IProblemRequestor { - override fun acceptProblem(problem: IProblem) {} - - override fun beginReporting() {} - - override fun endReporting() {} - - override fun isActive(): Boolean { - return true - } - } - val workingCopy = compilationUnit.getWorkingCopy(null) - val ast = workingCopy.reconcile(JLS8, ICompilationUnit.FORCE_PROBLEM_DETECTION - or ICompilationUnit.ENABLE_BINDINGS_RECOVERY or ICompilationUnit.ENABLE_STATEMENTS_RECOVERY, - object : WorkingCopyOwner() { - override fun getProblemRequestor(workingCopy: ICompilationUnit?): IProblemRequestor { - return requestor - } - }, NullProgressMonitor()) ?: return data - ast.accept(getVisitor(ast, ruleContext)) - - } catch (e: JavaModelException) { - throw RuntimeException(e) - } - - return data - } - - override fun setDescription(description: String?) { - try { - super.setDescription(P3cBundle.getMessage(description ?: "")) - } catch (e: MissingResourceException) { - super.setMessage(description) - } - - } - - override fun setMessage(message: String) { - try { - super.setMessage(P3cBundle.getMessage(message)) - } catch (e: MissingResourceException) { - super.setMessage(message) - } - - } - - - protected abstract fun getVisitor(ast: CompilationUnit, ruleContext: RuleContext): ASTVisitor - - internal fun addRuleViolation(ruleContext: RuleContext, ast: CompilationUnit, nodeInfo: NodeInfo) { - val rule = this - val ruleViolation = object : RuleViolation { - override fun getRule(): Rule { - return rule - } - - override fun getDescription(): String { - return getErrorMessage().trim { it <= ' ' } - } - - override fun isSuppressed(): Boolean { - return false - } - - override fun getFilename(): String { - return ruleContext.sourceCodeFilename - } - - override fun getBeginLine(): Int { - return ast.getLineNumber(nodeInfo.startPosition) - } - - override fun getBeginColumn(): Int { - return ast.getColumnNumber(nodeInfo.startPosition) - } - - override fun getEndLine(): Int { - return ast.getLineNumber(nodeInfo.endPosition) - } - - override fun getEndColumn(): Int { - return ast.getColumnNumber(nodeInfo.endPosition) - } - - override fun getPackageName(): String? { - return nodeInfo.packageName - } - - override fun getClassName(): String? { - return nodeInfo.className - } - - override fun getMethodName(): String? { - return nodeInfo.methodName - } - - override fun getVariableName(): String? { - return nodeInfo.variableName - } - - override fun toString(): String { - return rule.toString() - } - - - } - - ruleContext.report.addRuleViolation(ruleViolation) - } - - protected fun violation(rc: RuleContext, node: ASTNode, ast: CompilationUnit) { - val nodeInfo = NodeInfo() - nodeInfo.className = ast.javaElement.elementName - nodeInfo.packageName = ast.`package`.name.fullyQualifiedName - nodeInfo.startPosition = node.startPosition - nodeInfo.endPosition = node.startPosition + node.length - - addRuleViolation(rc, ast, nodeInfo) - } - - inner class NodeInfo { - internal var packageName: String? = null - internal var className: String? = null - internal var methodName: String? = null - internal var variableName: String? = null - internal var startPosition: Int = 0 - internal var endPosition: Int = 0 - } - - companion object { - val JLS8 = 8 - } -} diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/AvoidAccessStaticViaInstanceRule.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/AvoidAccessStaticViaInstanceRule.kt deleted file mode 100644 index 44d7fd7ef..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/AvoidAccessStaticViaInstanceRule.kt +++ /dev/null @@ -1,110 +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.smartfox.eclipse.pmd.rule - -import net.sourceforge.pmd.RuleContext -import org.eclipse.jdt.core.dom.ASTVisitor -import org.eclipse.jdt.core.dom.ClassInstanceCreation -import org.eclipse.jdt.core.dom.CompilationUnit -import org.eclipse.jdt.core.dom.FieldAccess -import org.eclipse.jdt.core.dom.IVariableBinding -import org.eclipse.jdt.core.dom.MethodInvocation -import org.eclipse.jdt.core.dom.Modifier -import org.eclipse.jdt.core.dom.QualifiedName -import org.eclipse.jdt.core.dom.SimpleName -import org.eclipse.jdt.core.dom.VariableDeclarationFragment - -/** - * @author caikang - * @date 2016/12/27 - */ -class AvoidAccessStaticViaInstanceRule : AbstractEclipseRule() { - override fun getVisitor(ast: CompilationUnit, ruleContext: RuleContext): ASTVisitor { - return object : ASTVisitor() { - override fun visit(node: QualifiedName?): Boolean { - val parent = node!!.parent - if (parent !is MethodInvocation && parent !is VariableDeclarationFragment) { - return false - } - val name = node.name - val binding = name.resolveBinding() - if (binding !is IVariableBinding || binding.getModifiers() and Modifier.STATIC == 0) { - return true - } - val qualifier = node.qualifier - val typeBinding = qualifier.resolveTypeBinding() - if (qualifier.isSimpleName) { - when (parent) { - is MethodInvocation -> { - val methodBinding = parent.resolveMethodBinding() - val methodTypeBinding = methodBinding.declaringClass - if (methodBinding.modifiers and Modifier.STATIC != 0 - && qualifier.fullyQualifiedName != methodTypeBinding.name - && methodTypeBinding == typeBinding && binding.name != typeBinding.name) { - violation(ruleContext, parent, ast) - return false - } - } - else -> { - } - } - if (typeBinding.name != qualifier.fullyQualifiedName) { - violation(ruleContext, node, ast) - return false - } - } - if (qualifier.isQualifiedName) { - val qualifiedName = qualifier as QualifiedName - if (typeBinding.name != qualifiedName.name.identifier) { - violation(ruleContext, node, ast) - return false - } - } - return true - } - - override fun visit(node: FieldAccess): Boolean { - val variableBinding = node.resolveFieldBinding() ?: return false - if (variableBinding.modifiers and Modifier.STATIC == 0) { - return true - } - if (node.expression is ClassInstanceCreation) { - violation(ruleContext, node, ast) - return true - } - return true - } - - override fun visit(node: MethodInvocation?): Boolean { - val methodBinding = node?.resolveMethodBinding() ?: return false - if (methodBinding.modifiers and Modifier.STATIC == 0) { - return true - } - if (node.expression is ClassInstanceCreation) { - violation(ruleContext, node, ast) - return true - } - val expression = node.expression - if (expression is SimpleName && expression.identifier != expression.resolveTypeBinding().name) { - violation(ruleContext, node, ast) - return true - } - return true - } - } - } - -} diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/AvoidUseDeprecationRule.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/AvoidUseDeprecationRule.kt deleted file mode 100644 index 8bd987139..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/AvoidUseDeprecationRule.kt +++ /dev/null @@ -1,107 +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.smartfox.eclipse.pmd.rule - -import net.sourceforge.pmd.RuleContext -import org.eclipse.jdt.core.dom.ASTVisitor -import org.eclipse.jdt.core.dom.ClassInstanceCreation -import org.eclipse.jdt.core.dom.CompilationUnit -import org.eclipse.jdt.core.dom.FieldAccess -import org.eclipse.jdt.core.dom.IVariableBinding -import org.eclipse.jdt.core.dom.ImportDeclaration -import org.eclipse.jdt.core.dom.MethodInvocation -import org.eclipse.jdt.core.dom.Modifier -import org.eclipse.jdt.core.dom.QualifiedName -import org.eclipse.jdt.core.dom.TypeDeclaration -import org.eclipse.jdt.core.dom.VariableDeclarationFragment - -/** - * @author caikang - * @date 2016/12/27 - */ -class AvoidUseDeprecationRule : AbstractEclipseRule() { - override fun getVisitor(ast: CompilationUnit, ruleContext: RuleContext): ASTVisitor { - return object : ASTVisitor() { - override fun visit(node: ImportDeclaration?): Boolean { - if (node!!.resolveBinding() != null && node.resolveBinding().isDeprecated) { - violation(ruleContext, node, ast) - } - return true - } - - override fun visit(node: QualifiedName?): Boolean { - if (node!!.parent !is MethodInvocation && node.parent !is VariableDeclarationFragment) { - return false - } - val name = node.name - val binding = name.resolveBinding() - if (binding !is IVariableBinding || binding.getModifiers() and Modifier.STATIC == 0) { - return true - } - if (binding.isDeprecated()) { - violation(ruleContext, node, ast) - return false - } - val qualifier = node.qualifier - val typeBinding = qualifier.resolveTypeBinding() - if (typeBinding.isDeprecated) { - violation(ruleContext, node, ast) - return false - } - return true - } - - override fun visit(node: TypeDeclaration?): Boolean { - val superClass = node!!.superclassType - if (superClass != null && superClass.resolveBinding().isDeprecated) { - violation(ruleContext, node, ast) - return true - } - val interfaces = node.resolveBinding().interfaces - for (tb in interfaces) { - if (tb.isDeprecated) { - violation(ruleContext, node, ast) - return true - } - } - return true - } - - override fun visit(node: FieldAccess?): Boolean { - val variableBinding = node!!.resolveFieldBinding() ?: return false - if (variableBinding.isDeprecated) { - violation(ruleContext, node, ast) - } - return true - } - - override fun visit(node: MethodInvocation): Boolean { - val methodBinding = node.resolveMethodBinding() ?: return false - if (methodBinding.isDeprecated) { - violation(ruleContext, node, ast) - } - return true - } - - override fun visit(node: ClassInstanceCreation?): Boolean { - if (node!!.resolveTypeBinding().isDeprecated) { - violation(ruleContext, node, ast) - } - return true - } - } - } -} diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/MapOrSetKeyShouldOverrideHashCodeEqualsRule.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/MapOrSetKeyShouldOverrideHashCodeEqualsRule.kt deleted file mode 100644 index 4ea226113..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/MapOrSetKeyShouldOverrideHashCodeEqualsRule.kt +++ /dev/null @@ -1,132 +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.smartfox.eclipse.pmd.rule - -import net.sourceforge.pmd.RuleContext -import org.eclipse.jdt.core.dom.ASTVisitor -import org.eclipse.jdt.core.dom.CompilationUnit -import org.eclipse.jdt.core.dom.ITypeBinding -import org.eclipse.jdt.core.dom.MethodInvocation -import org.eclipse.jdt.core.dom.VariableDeclarationStatement - -/** - * @author zenghou.fw - * @date 2016/12/27 - */ -class MapOrSetKeyShouldOverrideHashCodeEqualsRule : AbstractEclipseRule() { - - val methodEquals = "equals" - val methodHashCode = "hashCode" - val methodAdd = "add" - val methodPut = "put" - - private val skipJdkPackageJava = "java." - private val skipJdkPackageJavax = "javax." - - override fun getVisitor(ast: CompilationUnit, ruleContext: RuleContext): ASTVisitor { - return object : ASTVisitor() { - - override fun visit(node: VariableDeclarationStatement): Boolean { - if (!node.type.isParameterizedType) { - return true - } - val typeBinding = node.type.resolveBinding() - if (isSet(typeBinding) || isMap(typeBinding)) { - val argumentTypes = typeBinding.typeArguments - if (argumentTypes != null && argumentTypes.isNotEmpty()) { - if (!isOverrideEqualsAndHashCode(argumentTypes[0])) { - violation(ruleContext, node, ast) - return false - } - } - } - return true - } - - override fun visit(node: MethodInvocation): Boolean { - val methodBinding = node.resolveMethodBinding() ?: return false - val callerType = methodBinding.declaringClass - - if (methodAdd == methodBinding.name) { - if (!isSet(callerType)) { - return true - } - val parameterTypes = methodBinding.parameterTypes - if (parameterTypes != null && parameterTypes.isNotEmpty()) { - if (!isOverrideEqualsAndHashCode(parameterTypes[0])) { - violation(ruleContext, node, ast) - return false - } - } - return true - } - if (methodPut == methodBinding.name) { - if (!isMap(callerType)) { - return true - } - val parameterTypes = methodBinding.parameterTypes - if (parameterTypes != null && parameterTypes.isNotEmpty()) { - if (!isOverrideEqualsAndHashCode(parameterTypes[0])) { - violation(ruleContext, node, ast) - return false - } - } - } - return true - } - - private fun isOverrideEqualsAndHashCode(genericType: ITypeBinding): Boolean { - val skip = genericType.isEnum || genericType.isInterface || genericType.isArray - || genericType.isTypeVariable || genericType.isWildcardType - || genericType.qualifiedName?.startsWith(skipJdkPackageJava) ?: false - || genericType.qualifiedName?.startsWith(skipJdkPackageJavax) ?: false - // skip - if (skip) { - return true - } - - val methodBindings = genericType.declaredMethods ?: return false - - val overrideCount = methodBindings.asSequence().filter { - //find equals(Object o) and hashCode() with @Override - methodEquals == it.name || methodHashCode == it.name - }.filter { - when (it.name) { - methodEquals -> { - val parameterTypes = it.parameterTypes - parameterTypes != null && parameterTypes.isNotEmpty() - && Object::class.java.name == parameterTypes[0].qualifiedName - } - methodHashCode -> { - val parameterTypes = it.parameterTypes - parameterTypes == null || parameterTypes.isEmpty() - } - else -> false - } - }.count() - return overrideCount == 2 - } - - private fun isSet(typeBinding: ITypeBinding): Boolean { - return java.util.Set::class.java.name == typeBinding.binaryName - } - - private fun isMap(typeBinding: ITypeBinding): Boolean { - return java.util.Map::class.java.name == typeBinding.binaryName - } - } - } -} diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/MissingOverrideAnnotationRule.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/MissingOverrideAnnotationRule.kt deleted file mode 100644 index 5007be971..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/MissingOverrideAnnotationRule.kt +++ /dev/null @@ -1,84 +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.smartfox.eclipse.pmd.rule - -import com.alibaba.smartfox.eclipse.message.P3cBundle -import net.sourceforge.pmd.RuleContext -import org.eclipse.jdt.core.dom.ASTVisitor -import org.eclipse.jdt.core.dom.CompilationUnit -import org.eclipse.jdt.core.dom.MethodDeclaration -import org.eclipse.jdt.internal.compiler.lookup.MethodBinding -import java.util.Arrays -import javax.annotation.Generated - -/** - * @author caikang - * @date 2016/12/24 - */ -class MissingOverrideAnnotationRule : AbstractEclipseRule() { - override fun getErrorMessage(): String { - return P3cBundle.getMessage("rule.standalone.MissingOverrideAnnotationRule.error") - } - - override fun getVisitor(ast: CompilationUnit, ruleContext: RuleContext): ASTVisitor { - return MissingOverrideVisitor(ast, ruleContext) - } - - private inner class MissingOverrideVisitor(private val ast: CompilationUnit, - private val ruleContext: RuleContext) : ASTVisitor() { - - override fun visit(node: MethodDeclaration?): Boolean { - val methodBinding = node!!.resolveBinding() - val declaringClass = methodBinding.declaringClass ?: return super.visit(node) - if (declaringClass.isInterface) { - return super.visit(node) - } - val abs = methodBinding.annotations - if (abs.any { - Override::class.java.canonicalName == it.annotationType.binaryName - }) { - return super.visit(node) - } - try { - val field = methodBinding.javaClass.getDeclaredField("binding") - field.isAccessible = true - val internalBinding = field.get(methodBinding) as MethodBinding - if (internalBinding.isStatic || !(internalBinding.isImplementing || internalBinding.isOverriding) - || isGenerated(internalBinding)) { - return super.visit(node) - } - violation(ruleContext, node, ast) - } catch (e: Exception) { - e.printStackTrace() - } - - return super.visit(node) - } - - /** - * skip @Override check for generated code by lombok - * @param internalBinding - * @return - */ - private fun isGenerated(internalBinding: MethodBinding): Boolean { - val annotationBindings = internalBinding.annotations ?: return false - return annotationBindings.any { - it.annotationType != null && Arrays.equals(Generated::class.java.name.toCharArray(), - it.annotationType.readableName()) - } - } - } -} diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/AllRulesPreferencePage.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/AllRulesPreferencePage.kt deleted file mode 100644 index c7acc8e0d..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/AllRulesPreferencePage.kt +++ /dev/null @@ -1,36 +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.smartfox.eclipse.ui - -import org.eclipse.jface.preference.PreferencePage -import org.eclipse.swt.widgets.Composite -import org.eclipse.swt.widgets.Control -import org.eclipse.ui.IWorkbench -import org.eclipse.ui.IWorkbenchPreferencePage - -/** - * - * @author caikang - * @date 2017/09/01 - */ -class AllRulesPreferencePage : PreferencePage(), IWorkbenchPreferencePage { - override fun init(parent: IWorkbench?) { - } - - override fun createContents(parent: Composite): Control { - return AllRulesView(parent).content - } -} \ No newline at end of file diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/AllRulesView.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/AllRulesView.kt deleted file mode 100644 index b7578d441..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/AllRulesView.kt +++ /dev/null @@ -1,49 +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.smartfox.eclipse.ui - -import com.alibaba.smartfox.eclipse.SmartfoxActivator -import org.eclipse.swt.SWT -import org.eclipse.swt.layout.FillLayout -import org.eclipse.swt.widgets.Composite -import org.eclipse.swt.widgets.List - - -/** - * - * @author caikang - * @date 2017/09/01 - */ -class AllRulesView(parent: Composite) { - val content = Composite(parent, SWT.NONE) - - private val ruleList = SmartfoxActivator.instance.ruleSets.allRules.toList() - - init { - content.layout = FillLayout() - val list = List(content, SWT.BORDER or SWT.SINGLE or SWT.V_SCROLL or SWT.PUSH or SWT.H_SCROLL) - ruleList.forEach { - list.add(it.message) - } - val ruleDetail = RuleDetailComposite(content, SWT.PUSH) - list.addListener(SWT.Selection) { - val index = list.selectionIndex - val rule = ruleList.getOrNull(index) ?: return@addListener - ruleDetail.refresh(rule) - } - list.select(0) - } -} \ No newline at end of file diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/InspectionResultTreeContentProvider.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/InspectionResultTreeContentProvider.kt deleted file mode 100644 index 26e541a04..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/InspectionResultTreeContentProvider.kt +++ /dev/null @@ -1,68 +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.smartfox.eclipse.ui - -import org.eclipse.jface.viewers.ITreeContentProvider -import org.eclipse.jface.viewers.Viewer - -/** - * - * - * @author caikang - * @date 2017/06/08 - */ -object InspectionResultTreeContentProvider : ITreeContentProvider { - private lateinit var input: InspectionResults - - override fun getParent(element: Any?): Any { - return input - } - - override fun hasChildren(element: Any?): Boolean { - return element is InspectionResults || element is LevelViolations || element is RuleViolations - || element is FileMarkers - } - - override fun getChildren(parentElement: Any?): Array { - if (parentElement is InspectionResults) { - return parentElement.errors.toTypedArray() - } - if (parentElement is LevelViolations) { - return parentElement.rules.toTypedArray() - } - if (parentElement is RuleViolations) { - return parentElement.files.toTypedArray() - } - if (parentElement is FileMarkers) { - return parentElement.markers.toTypedArray() - } - return emptyArray() - } - - override fun getElements(inputElement: Any?): Array { - return input.errors.toTypedArray() - } - - override fun inputChanged(viewer: Viewer?, oldInput: Any?, newInput: Any?) { - if (newInput == null) { - return - } - this.input = newInput as InspectionResults - } - - override fun dispose() { - } -} \ No newline at end of file diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/InspectionResultTreeLabelProvider.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/InspectionResultTreeLabelProvider.kt deleted file mode 100644 index 286ce0a83..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/InspectionResultTreeLabelProvider.kt +++ /dev/null @@ -1,65 +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.smartfox.eclipse.ui - -import com.alibaba.smartfox.eclipse.SmartfoxActivator -import com.alibaba.smartfox.eclipse.pmd.RulePriority -import org.eclipse.jface.viewers.LabelProvider -import org.eclipse.swt.graphics.Image - -/** - * - * - * @author caikang - * @date 2017/06/08 - */ -object InspectionResultTreeLabelProvider : LabelProvider() { - override fun getImage(element: Any?): Image? { - if (element is LevelViolations) { - val imageName = when (element.level) { - RulePriority.Blocker.title, RulePriority.Critical.title -> "${element.level}.gif".toLowerCase() - else -> "${element.level}.png".toLowerCase() - } - return SmartfoxActivator.instance.getImage("icons/view/$imageName") - } - if (element is FileMarkers) { - if (element.file.fullPath.toPortableString().endsWith("java")) { - return SmartfoxActivator.instance.getImage("icons/view/class_obj.png") - } - return SmartfoxActivator.instance.getImage("icons/view/file_obj.png") - } - return null - } - - override fun getText(element: Any?): String { - if (element is LevelViolations) { - return "${element.level} (${element.count} Violations)" - } - if (element is RuleViolations) { - val rule = SmartfoxActivator.instance.getRule(element.rule) - return "${rule.message} (${element.count} Violations)" - } - if (element is FileMarkers) { - return element.file.fullPath.toPortableString().substringAfterLast("/") + - " (${element.markers.size} Violations)" - } - if (element is MarkerViolation) { - val desc = element.violation.description - return "$desc (at line ${element.violation.beginLine})" - } - return element.toString() - } -} \ No newline at end of file diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/InspectionResultView.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/InspectionResultView.kt deleted file mode 100644 index ac5dbcdc3..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/InspectionResultView.kt +++ /dev/null @@ -1,249 +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.smartfox.eclipse.ui - -import com.alibaba.smartfox.eclipse.SmartfoxActivator -import com.alibaba.smartfox.eclipse.job.P3cMutex -import com.alibaba.smartfox.eclipse.util.MarkerUtil -import org.eclipse.core.resources.IFile -import org.eclipse.core.resources.IMarker -import org.eclipse.core.runtime.IProgressMonitor -import org.eclipse.core.runtime.IStatus -import org.eclipse.core.runtime.Status -import org.eclipse.core.runtime.jobs.Job -import org.eclipse.jface.action.Action -import org.eclipse.jface.action.Separator -import org.eclipse.jface.util.OpenStrategy -import org.eclipse.jface.viewers.ISelection -import org.eclipse.jface.viewers.IStructuredSelection -import org.eclipse.jface.viewers.ITreeSelection -import org.eclipse.jface.viewers.TreeViewer -import org.eclipse.swt.SWT -import org.eclipse.swt.layout.FillLayout -import org.eclipse.swt.widgets.Composite -import org.eclipse.swt.widgets.Display -import org.eclipse.ui.IWorkbenchPage -import org.eclipse.ui.OpenAndLinkWithEditorHelper -import org.eclipse.ui.PartInitException -import org.eclipse.ui.PlatformUI -import org.eclipse.ui.ide.IDE -import org.eclipse.ui.ide.ResourceUtil -import org.eclipse.ui.internal.views.markers.MarkerSupportInternalUtilities -import org.eclipse.ui.part.ViewPart -import org.eclipse.ui.texteditor.ITextEditor -import java.util.HashSet - -/** - * - * - * @author caikang - * @date 2017/06/08 - */ -class InspectionResultView : ViewPart() { - lateinit var treeViewer: TreeViewer - - private val quickFixAction = QuickFixAction(this) - - override fun setFocus() { - treeViewer.control.setFocus() - } - - override fun createPartControl(parent: Composite) { - parent.layout = FillLayout() - treeViewer = TreeViewer(parent, SWT.MULTI or SWT.H_SCROLL or SWT.V_SCROLL) - treeViewer.setUseHashlookup(true) - treeViewer.contentProvider = InspectionResultTreeContentProvider - treeViewer.labelProvider = InspectionResultTreeLabelProvider - treeViewer.input = InspectionResults - - InspectionResults.view = this - - addDoubleClickListener() - - addSelectionChangedListener() - - initToolBar() - - addLinkWithEditorSupport() - site.selectionProvider = treeViewer - } - - fun clear() { - InspectionResults.clear() - refreshView(InspectionResults) - } - - fun refreshView(input: InspectionResults) { - Display.getDefault().asyncExec { - treeViewer.refresh(input, true) - contentDescription = input.contentDescription - } - } - - private fun addSelectionChangedListener() { - treeViewer.addSelectionChangedListener inner@ { - val selection = it.selection as? IStructuredSelection ?: return@inner - val item = selection.firstElement ?: return@inner - val ruleDetailView = RuleDetailView.showAndGetView() - when (item) { - is MarkerViolation -> { - ruleDetailView.refresh(item.violation.rule) - quickFixAction.updateFileMarkers(listOf(FileMarkers(item.marker.resource as IFile, listOf(item)))) - } - is FileMarkers -> { - ruleDetailView.refresh(item.markers.first().violation.rule) - quickFixAction.updateFileMarkers(listOf(item)) - } - is RuleViolations -> { - ruleDetailView.refresh(SmartfoxActivator.instance.getRule(item.rule)) - quickFixAction.updateFileMarkers(item.files) - } - else -> { - quickFixAction.updateFileMarkers(emptyList()) - } - } - } - } - - private fun initToolBar() { - val bars = viewSite.actionBars - val tm = bars.toolBarManager - - val clearAction = object : Action("Clear Markers") { - override fun run() { - val job = object : Job("Clear Markers") { - override fun run(monitor: IProgressMonitor): IStatus { - if (monitor.isCanceled) { - Status.CANCEL_STATUS - } - clear() - return Status.OK_STATUS - } - } - job.rule = P3cMutex - job.schedule() - } - } - - clearAction.imageDescriptor = SmartfoxActivator.getImageDescriptor("icons/actions/clear.png") - - tm.add(Separator("Markers")) - tm.add(clearAction) - - tm.add(Separator("FilterGroup")) - tm.add(quickFixAction) - } - - private fun addLinkWithEditorSupport() { - object : OpenAndLinkWithEditorHelper(treeViewer) { - override fun activate(selection: ISelection) { - val currentMode = OpenStrategy.getOpenMethod() - try { - OpenStrategy.setOpenMethod(OpenStrategy.DOUBLE_CLICK) - openSelectedMarkers() - } finally { - OpenStrategy.setOpenMethod(currentMode) - } - } - - override fun linkToEditor(selection: ISelection?) { - } - - override fun open(selection: ISelection, activate: Boolean) { - val structured = selection as ITreeSelection - val element = structured.firstElement as? MarkerViolation ?: return - val page = site.page - if (element.marker.exists()) { - openMarkerInEditor(element.marker, page) - return - } - val file = element.marker.resource as IFile - val editor = IDE.openEditor(page, file) as ITextEditor - editor.selectAndReveal(MarkerUtil.getAbsoluteRange(file, element.violation).start, 0) - } - } - } - - internal fun openSelectedMarkers() { - val markers = getOpenableMarkers() - for (marker in markers) { - val page = site.page - openMarkerInEditor(marker, page) - } - } - - private fun getOpenableMarkers(): Array { - val structured = treeViewer.selection as ITreeSelection - val elements = structured.iterator() - val result = HashSet() - - while (elements.hasNext()) { - val marker = elements.next() as? IMarker ?: return emptyArray() - result.add(marker) - } - return result.toTypedArray() - } - - - fun openMarkerInEditor(marker: IMarker?, page: IWorkbenchPage) { - val editor = page.activeEditor - if (editor != null) { - val input = editor.editorInput - val file = ResourceUtil.getFile(input) - if (file != null) { - if (marker!!.resource == file && OpenStrategy.activateOnOpen()) { - page.activate(editor) - } - } - } - - if (marker != null && marker.resource is IFile) { - try { - IDE.openEditor(page, marker, OpenStrategy.activateOnOpen()) - } catch (e: PartInitException) { - MarkerSupportInternalUtilities.showViewError(e) - } - - } - } - - private fun addDoubleClickListener() { - treeViewer.addDoubleClickListener({ event -> - val selection = event.selection - if (selection !is ITreeSelection || selection.size() != 1) { - return@addDoubleClickListener - } - val obj = selection.firstElement - if (treeViewer.isExpandable(obj)) { - treeViewer.setExpandedState(obj, !treeViewer.getExpandedState(obj)) - } - }) - } - - companion object { - val viewId = "com.alibaba.smartfox.eclipse.ui.InspectionResultView" - - fun activeViews() { - PlatformUI.getWorkbench().activeWorkbenchWindow.activePage.showView(viewId) - RuleDetailView.showAndGetView() - } - - fun getView(): InspectionResultView { - return PlatformUI.getWorkbench().activeWorkbenchWindow.activePage.findView(viewId) as InspectionResultView - } - } -} - diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/InspectionResults.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/InspectionResults.kt deleted file mode 100644 index 3e1482081..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/InspectionResults.kt +++ /dev/null @@ -1,103 +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.smartfox.eclipse.ui - -import com.alibaba.smartfox.eclipse.pmd.RulePriority -import com.alibaba.smartfox.eclipse.util.MarkerUtil -import org.eclipse.core.resources.IFile -import org.eclipse.core.resources.IMarker - -/** - * - * - * @author caikang - * @date 2017/06/13 - */ -object InspectionResults { - private val fileViolations = linkedMapOf>() - - var contentDescription = "" - - val errors: List - get() { - val result = toLevelViolationList(fileViolations.values.flatten()) - contentDescription = getContentDescription(result) - return result - } - - lateinit var view: InspectionResultView - - - fun clear() { - fileViolations.forEach { - MarkerUtil.removeAllMarkers(it.key) - } - fileViolations.clear() - // update contentDescription - errors - } - - private fun toLevelViolationList(markers: Collection): List { - return markers.groupBy { - it.violation.rule.priority.priority - }.mapValues { - it.value.groupBy { - it.violation.rule.name - }.mapValues { - it.value.groupBy { - it.marker.resource as IFile - }.map { - FileMarkers(it.key, it.value) - } - }.map { - RuleViolations(it.key, it.value) - } - }.toSortedMap().map { - val level = RulePriority.valueOf(it.key).title - LevelViolations(level, it.value) - } - } - - fun updateFileViolations(file: IFile, markers: List) { - if (markers.isEmpty()) { - fileViolations.remove(file) - } else { - fileViolations[file] = markers - } - view.refreshView(this) - } - - fun removeMarker(marker: IMarker) { - val file = marker.resource as IFile - val list = fileViolations[file] ?: return - val result = list.filter { - it.marker != marker - } - fileViolations[file] = result - marker.delete() - view.refreshView(this) - } - - fun getContentDescription(errors: List): String { - val map = errors.associateBy { - it.level - } - - return "${map[RulePriority.Blocker.title]?.count ?: 0} Blockers," + - "${map[RulePriority.Critical.title]?.count ?: 0} Criticals," + - "${map[RulePriority.Major.title]?.count ?: 0} Majors" - } -} diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/QuickFixAction.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/QuickFixAction.kt deleted file mode 100644 index 9dfb33d77..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/QuickFixAction.kt +++ /dev/null @@ -1,114 +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.smartfox.eclipse.ui - -import com.alibaba.p3c.pmd.lang.java.rule.flowcontrol.NeedBraceRule -import com.alibaba.smartfox.eclipse.RunWithoutViewRefresh -import com.alibaba.smartfox.eclipse.SmartfoxActivator -import com.alibaba.smartfox.eclipse.job.CodeAnalysis -import com.alibaba.smartfox.eclipse.job.P3cMutex -import com.alibaba.smartfox.eclipse.pmd.rule.MissingOverrideAnnotationRule -import com.alibaba.smartfox.eclipse.util.CleanUps -import com.alibaba.smartfox.eclipse.util.getResolution -import org.eclipse.core.runtime.IProgressMonitor -import org.eclipse.core.runtime.IStatus -import org.eclipse.core.runtime.Status -import org.eclipse.core.runtime.SubMonitor -import org.eclipse.core.runtime.jobs.Job -import org.eclipse.jface.action.Action - -/** - * - * - * @author caikang - * @date 2017/06/14 - */ -class QuickFixAction(val view: InspectionResultView) : Action("Quick Fix") { - init { - imageDescriptor = SmartfoxActivator.getImageDescriptor("icons/actions/quickfixBulb.png") - isEnabled = false - } - - var markers = listOf() - - fun updateFileMarkers(markers: List) { - this.markers = markers - isEnabled = enabled() - } - - override fun run() { - if (markers.isEmpty()) { - return - } - runJob() - } - - private fun runJob() { - val job = object : Job("Perform P3C Quick Fix") { - override fun run(monitor: IProgressMonitor): IStatus { - val subMonitor = SubMonitor.convert(monitor, markers.size) - monitor.setTaskName("Process File") - markers.forEach { - if (monitor.isCanceled) { - return@run Status.CANCEL_STATUS - } - monitor.subTask(it.file.name) - val childMonitor = subMonitor.newChild(1) - if (useCleanUpRefactoring()) { - CleanUps.fix(it.file, childMonitor) - } else { - it.markers.filter { it.marker.exists() }.forEach { - (it.marker.getResolution() as RunWithoutViewRefresh).run(it.marker, true) - } - } - val markers = CodeAnalysis.processFileToMakers(it.file, monitor) - InspectionResults.updateFileViolations(it.file, markers) - } - - return Status.OK_STATUS - } - } - val outJob = object:Job("P3C Quick Fix Wait analysis finish"){ - override fun run(monitor: IProgressMonitor?): IStatus { - job.schedule() - return Status.OK_STATUS - } - } - outJob.rule = P3cMutex - outJob.schedule() - - } - - fun enabled(): Boolean { - if (useCleanUpRefactoring()) { - return true - } - if (markers.isEmpty()) { - return false - } - val marker = markers.first().markers.first().marker - return marker.exists() && marker.getResolution() != null - } - - private fun useCleanUpRefactoring(): Boolean { - if (markers.isEmpty()) { - return false - } - val ruleName = markers.first().markers.first().violation.rule.name - return ruleName == MissingOverrideAnnotationRule::class.java.simpleName - || ruleName == NeedBraceRule::class.java.simpleName - } -} diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/RuleDetailComposite.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/RuleDetailComposite.kt deleted file mode 100644 index 667e276ee..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/RuleDetailComposite.kt +++ /dev/null @@ -1,83 +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.smartfox.eclipse.ui - -import com.alibaba.smartfox.eclipse.pmd.RulePriority -import com.alibaba.smartfox.eclipse.ui.pmd.ContentBuilder -import com.alibaba.smartfox.eclipse.ui.pmd.StringArranger -import net.sourceforge.pmd.Rule -import org.eclipse.swt.SWT -import org.eclipse.swt.custom.StyledText -import org.eclipse.swt.layout.FillLayout -import org.eclipse.swt.widgets.Composite - -/** - * - * @author caikang - * @date 2017/09/01 - */ -class RuleDetailComposite(parent: Composite, style: Int = SWT.NONE) { - private val viewField: StyledText - private val contentBuilder = ContentBuilder() - private val arranger = StringArranger(" ") - private val panel = Composite(parent, style) - - init { - panel.layout = FillLayout() - - viewField = StyledText(panel, SWT.BORDER or SWT.H_SCROLL or SWT.V_SCROLL) - viewField.wordWrap = true - viewField.tabs = 20 - viewField.text = "Select a result item to show rule detail." - viewField.editable = false - } - - fun refresh(rule: Rule) { - contentBuilder.clear() - viewField.text = "" - contentBuilder.addHeading("Name") - contentBuilder.addText(rule.name) - contentBuilder.addHeading("Severity") - contentBuilder.addText(RulePriority.valueOf(rule.priority.priority).title) - contentBuilder.addHeading("Message") - contentBuilder.addText(rule.message) - if (!rule.description.isNullOrBlank()) { - contentBuilder.addHeading("Description") - contentBuilder.addRawText(arranger.format(rule.description).toString()) - } - - val examples = rule.examples - if (examples.isEmpty()) { - contentBuilder.showOn(viewField) - return - } - - contentBuilder.setLanguage(rule.language) - - contentBuilder.addHeading("Examples") - contentBuilder.addText("") - for (example in rule.examples) { - contentBuilder.addCode(example.trim { it <= ' ' }) - contentBuilder.addText("") - } - contentBuilder.showOn(viewField) - - if (contentBuilder.hasLinks()) { - contentBuilder.addLinkHandler(viewField) - } - viewField.update() - } -} \ No newline at end of file diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/RuleDetailView.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/RuleDetailView.kt deleted file mode 100644 index 915adf798..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/RuleDetailView.kt +++ /dev/null @@ -1,92 +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.smartfox.eclipse.ui - -import com.alibaba.smartfox.eclipse.SmartfoxActivator -import net.sourceforge.pmd.Rule -import org.eclipse.jface.action.Action -import org.eclipse.jface.action.Separator -import org.eclipse.swt.SWT -import org.eclipse.swt.custom.ScrolledComposite -import org.eclipse.swt.layout.FillLayout -import org.eclipse.swt.widgets.Composite -import org.eclipse.swt.widgets.Display -import org.eclipse.swt.widgets.Shell -import org.eclipse.ui.IWorkbenchPage -import org.eclipse.ui.PlatformUI -import org.eclipse.ui.part.ViewPart - - -/** - * - * - * @author caikang - * @date 2017/06/12 - */ -open class RuleDetailView : ViewPart() { - - private lateinit var ruleDetailComposite: RuleDetailComposite - - override fun setFocus() { - } - - override fun createPartControl(parent: Composite) { - ruleDetailComposite = RuleDetailComposite(parent) - initToolBar() - } - - fun refresh(rule: Rule) { - ruleDetailComposite.refresh(rule) - } - - - private fun initToolBar() { - val bars = viewSite.actionBars - val tm = bars.toolBarManager - - val rulesAction = object : Action("Show Rules") { - override fun run() { - val shell = Shell(Display.getDefault()) - shell.text = "All Rules" - shell.layout = FillLayout() - - val sc = ScrolledComposite(shell, SWT.V_SCROLL or SWT.H_SCROLL) - - val rulesView = AllRulesView(sc) - - sc.expandHorizontal = true - sc.expandVertical = true - - sc.content = rulesView.content - - shell.open() - } - } - - rulesAction.imageDescriptor = SmartfoxActivator.getImageDescriptor("icons/actions/rules.png") - - tm.add(Separator("Markers")) - tm.add(rulesAction) - } - - companion object { - fun showAndGetView(): RuleDetailView { - return PlatformUI.getWorkbench().activeWorkbenchWindow.activePage.showView( - "com.alibaba.smartfox.eclipse.ui.RuleDetailView", null, - IWorkbenchPage.VIEW_VISIBLE) as RuleDetailView - } - } -} diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/Violations.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/Violations.kt deleted file mode 100644 index ddb7a098d..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/Violations.kt +++ /dev/null @@ -1,86 +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.smartfox.eclipse.ui - -import com.alibaba.smartfox.eclipse.util.MarkerUtil -import net.sourceforge.pmd.RuleViolation -import org.eclipse.core.resources.IFile -import org.eclipse.core.resources.IMarker - -/** - * - * - * @author caikang - * @date 2017/06/13 - */ -data class LevelViolations(var level: String, var rules: List, - var count: Int = rules.sumBy { it.count }) { - fun removeMarkers() { - rules.forEach { - it.removeMarkers() - } - } - - override fun equals(other: Any?): Boolean { - if (other !is LevelViolations) { - return false - } - return level == other.level - } - - override fun hashCode(): Int { - return level.hashCode() - } -} - -data class RuleViolations(var rule: String, var files: List, - var count: Int = files.sumBy { it.markers.size }) { - fun removeMarkers() { - files.forEach { - it.removeMarkers() - } - } - - override fun equals(other: Any?): Boolean { - if (other !is RuleViolations) { - return false - } - return rule == other.rule - } - - override fun hashCode(): Int { - return rule.hashCode() - } -} - -data class FileMarkers(var file: IFile, var markers: List) { - fun removeMarkers() { - MarkerUtil.removeAllMarkers(file) - } - - override fun equals(other: Any?): Boolean { - if (other !is FileMarkers) { - return false - } - return file == other.file - } - - override fun hashCode(): Int { - return file.hashCode() - } -} - -data class MarkerViolation(val marker: IMarker, val violation: RuleViolation) diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/BasicLineStyleListener.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/BasicLineStyleListener.kt deleted file mode 100644 index aff3777b8..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/BasicLineStyleListener.kt +++ /dev/null @@ -1,20 +0,0 @@ -package com.alibaba.smartfox.eclipse.ui.pmd - -import org.eclipse.swt.custom.LineStyleEvent -import org.eclipse.swt.custom.LineStyleListener - -/** - * This class performs the syntax highlighting and styling for Pmpe - * * PmpeLineStyleListener constructor - - * @param theSyntaxData the syntax data to use - */ -class BasicLineStyleListener(theSyntaxData: SyntaxData) : StyleExtractor(theSyntaxData), LineStyleListener { - /** - * Called by StyledText to get styles for a line - */ - override fun lineGetStyle(event: LineStyleEvent) { - val styles = lineStylesFor(event.lineText, event.lineOffset, event.lineText.length) - event.styles = styles.toTypedArray() - } -} diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/ContentBuilder.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/ContentBuilder.kt deleted file mode 100644 index 21ca57259..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/ContentBuilder.kt +++ /dev/null @@ -1,158 +0,0 @@ -package com.alibaba.smartfox.eclipse.ui.pmd - -import net.sourceforge.pmd.lang.Language -import org.eclipse.swt.SWT -import org.eclipse.swt.custom.StyleRange -import org.eclipse.swt.custom.StyledText -import org.eclipse.swt.graphics.Point -import org.eclipse.swt.widgets.Display -import org.eclipse.ui.PlatformUI -import java.net.URL -import java.util.ArrayList -import java.util.Arrays -import java.util.HashMap - -/** - * - * @author caikang - * @date 2017/07/20 - */ -class ContentBuilder { - private val CR = '\n' - private val buffer = StringBuilder() - private val headingSpans = ArrayList() - private val codeSpans = ArrayList() - private val linksBySpan = HashMap() - - private val indentDepth: Int = 3 - - private val codeStyleExtractor = StyleExtractor(SyntaxManager.getSyntaxData("java")) - - private val background = Display.getCurrent().getSystemColor(SWT.COLOR_WHITE) - - private val headingColor = Display.getCurrent().getSystemColor(SWT.COLOR_BLUE) - - private val codeStyle = FontBuilder("Courier", 11, SWT.NORMAL).style(Display.getCurrent()) - - fun clear() { - buffer.setLength(0) - headingSpans.clear() - codeSpans.clear() - linksBySpan.clear() - } - - fun addHeading(heading: String) { - var length = buffer.length - if (length > 0) { - buffer.append(CR) - length += 1 - } - - headingSpans.add(intArrayOf(length, length + heading.length)) - buffer.append(heading).append(CR) - } - - fun addText(text: String) { - for (i in 0 until indentDepth) { - buffer.append(' ') - } - buffer.append(text).append(CR) - } - - fun addRawText(text: String) { - buffer.append(text) - } - - fun addCode(code: String) { - val length = buffer.length - codeSpans.add(intArrayOf(length, length + code.length)) - buffer.append(code) - } - - fun setLanguage(language: Language) { - val syntax = SyntaxManager.getSyntaxData(language.terseName) - codeStyleExtractor.syntax(syntax) - } - - fun hasLinks(): Boolean { - return linksBySpan.isNotEmpty() - } - - fun addLinkHandler(widget: StyledText) { - - widget.addListener(SWT.MouseDown) { event -> - // It is up to the application to determine when and how a link - // should be activated. - // In this snippet links are activated on mouse down when the - // control key is held down - // if ((event.stateMask & SWT.MOD1) != 0) { - try { - val offset = widget.getOffsetAtLocation(Point(event.x, event.y)) - val link = linkAt(offset) - if (link != null) { - launchBrowser(link) - } - - } catch (e: IllegalArgumentException) { - // no character under event.x, event.y - } - } - } - - private fun linkAt(textIndex: Int): String? { - var span: IntArray - for ((key, value) in linksBySpan) { - span = key - if (span[0] <= textIndex && textIndex <= span[1]) { - return value - } - } - return null - } - - private fun launchBrowser(link: String) { - try { - val browser = PlatformUI.getWorkbench().browserSupport.externalBrowser - browser.openURL(URL(link)) - } catch (ex: Exception) { - ex.printStackTrace() - } - } - - fun showOn(widget: StyledText) { - val text = buffer.toString() - widget.text = text - val ranges = ArrayList() - var span: IntArray - for (i in headingSpans.indices) { - span = headingSpans[i] - ranges.add(StyleRange(span[0], span[1] - span[0], headingColor, background, SWT.BOLD)) - } - for (spn in linksBySpan.keys) { - val style = StyleRange(spn[0], spn[1] - spn[0], headingColor, background, SWT.UNDERLINE_LINK) - style.underline = true - ranges.add(style) - } - val crStr = Character.toString(CR) - var sr: StyleRange - - for (i in codeSpans.indices) { - span = codeSpans[i] - sr = StyleRange(codeStyle) - sr.start = span[0] - sr.length = span[1] - span[0] - - val colorRanges = codeStyleExtractor.stylesFor(text, sr.start, sr.length, crStr) - ranges += colorRanges - } - // must be in order! - val styles = sort(ranges) - widget.styleRanges = styles - } - - private fun sort(ranges: List): Array { - val styles = ranges.toTypedArray() - Arrays.sort(styles) { sr1, sr2 -> sr1.start - sr2.start } - return styles - } -} \ No newline at end of file diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/FontBuilder.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/FontBuilder.kt deleted file mode 100644 index 75b61359a..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/FontBuilder.kt +++ /dev/null @@ -1,19 +0,0 @@ -package com.alibaba.smartfox.eclipse.ui.pmd - -import org.eclipse.swt.graphics.Font -import org.eclipse.swt.graphics.TextStyle -import org.eclipse.swt.widgets.Display - -/** - * @author Brian Remedios - */ -class FontBuilder(val name: String, val size: Int, val style: Int, val colorIdx: Int = -1) { - - fun build(display: Display): Font { - return Font(display, name, size, style) - } - - fun style(display: Display): TextStyle { - return TextStyle(build(display), if (colorIdx < 0) null else display.getSystemColor(colorIdx), null) - } -} diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/StringArranger.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/StringArranger.kt deleted file mode 100644 index 78cd5ae54..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/StringArranger.kt +++ /dev/null @@ -1,54 +0,0 @@ -package com.alibaba.smartfox.eclipse.ui.pmd - -import net.sourceforge.pmd.util.StringUtil -import java.util.ArrayList - -/** - * @author Brian Remedios - */ -class StringArranger(private val indentString: String) { - - fun withIndent(rawText: String): String { - return indentString + rawText - } - - fun format(rawText: String): StringBuilder { - - val sb = StringBuilder() - for (line in trimmedLinesIn(rawText)) { - sb.append(indentString) - sb.append(line).append(CR) - } - - return sb - } - - fun trimmedLinesIn(text: String): List { - - val lines = text.split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() - if (lines.isEmpty()) { - return emptyList() - } - - val lineSet = ArrayList(lines.size) - - var startLine = 0 - while (startLine < lines.size && StringUtil.isEmpty(lines[startLine])) { - startLine++ - } - - var endLine = lines.size - 1 - while (endLine >= 0 && StringUtil.isEmpty(lines[endLine])) { - endLine-- - } - - lines.mapTo(lineSet) { - it.trim { it <= ' ' } - } - return lineSet - } - - companion object { - private val CR = '\n' - } -} diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/StyleExtractor.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/StyleExtractor.kt deleted file mode 100644 index 07b8821e6..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/StyleExtractor.kt +++ /dev/null @@ -1,275 +0,0 @@ -package com.alibaba.smartfox.eclipse.ui.pmd - -import net.sourceforge.pmd.util.StringUtil -import org.eclipse.swt.SWT -import org.eclipse.swt.custom.StyleRange -import org.eclipse.swt.widgets.Display -import java.util.ArrayList -import java.util.LinkedList - -/** - * @author Brian Remedios - */ -open class StyleExtractor(private var syntaxData: SyntaxData?) { - private val commentOffsets: MutableList - - init { - commentOffsets = LinkedList() - } - - fun syntax(theSyntax: SyntaxData?) { - syntaxData = theSyntax - } - - /** - * Refreshes the offsets for all multiline comments in the parent - * StyledText. The parent StyledText should call this whenever its text is - * modified. Note that this code doesn't ignore comment markers inside - * strings. - - * @param text the text from the StyledText - */ - fun refreshMultilineComments(text: String) { - // Clear any stored offsets - commentOffsets.clear() - - if (syntaxData != null) { - // Go through all the instances of COMMENT_START - var pos = text.indexOf(syntaxData!!.multiLineCommentStart!!) - while (pos > -1) { - // offsets[0] holds the COMMENT_START offset - // and COMMENT_END holds the ending offset - val offsets = IntArray(2) - offsets[0] = pos - - // Find the corresponding end comment. - pos = text.indexOf(syntaxData!!.multiLineCommentEnd!!, pos) - - // If no corresponding end comment, use the end of the text - offsets[1] = if (pos == -1) text.length - 1 else pos + syntaxData!!.multiLineCommentEnd!!.length - 1 - pos = offsets[1] - // Add the offsets to the collection - commentOffsets.add(offsets) - pos = text.indexOf(syntaxData!!.multiLineCommentStart!!, pos) - } - } - } - - /** - * Checks to see if the specified section of text begins inside a multiline - * comment. Returns the index of the closing comment, or the end of the line - * if the whole line is inside the comment. Returns -1 if the line doesn't - * begin inside a comment. - - * @param start the starting offset of the text - * @param length the length of the text - * @return int - */ - private fun getBeginsInsideComment(start: Int, length: Int): Int { - // Assume section doesn't being inside a comment - var index = -1 - - // Go through the multiline comment ranges - var i = 0 - val n = commentOffsets.size - while (i < n) { - val offsets = commentOffsets[i] - - // If starting offset is past range, quit - if (offsets[0] > start + length) { - break - } - // Check to see if section begins inside a comment - if (offsets[0] <= start && offsets[1] >= start) { - // It does; determine if the closing comment marker is inside - // this section - index = if (offsets[1] > start + length) start + length - else offsets[1] + syntaxData!!.multiLineCommentEnd!!.length - 1 - } - i++ - } - return index - } - - private fun isDefinedVariable(text: String): Boolean { - return StringUtil.isNotEmpty(text) - } - - private fun atMultiLineCommentStart(text: String, position: Int): Boolean { - return text.indexOf(syntaxData!!.multiLineCommentStart!!, position) == position - } - - private fun atStringStart(text: String, position: Int): Boolean { - return text.indexOf(syntaxData!!.stringStart!!, position) == position - } - - private fun atVarnameReference(text: String, position: Int): Boolean { - return syntaxData!!.varnameReference != null && text.indexOf(syntaxData!!.varnameReference!!, - position) == position - } - - private fun atSingleLineComment(text: String, position: Int): Boolean { - return syntaxData!!.comment != null && text.indexOf(syntaxData!!.comment!!, position) == position - } - - private fun getKeywordEnd(lineText: String, start: Int): Int { - - val length = lineText.length - - val buf = StringBuilder(length) - var i = start - - // Call any consecutive letters a word - while (i < length && Character.isLetter(lineText[i])) { - buf.append(lineText[i]) - i++ - } - - return if (syntaxData!!.isKeyword(buf.toString())) i else 0 - i - } - - /** - * Chop up the text into individual lines starting from offset and then - * determine the required styles for each. Ensures the offset is properly - * accounted for in each. - - * @param text - * @param offset - * @param length - * @return - */ - fun stylesFor(text: String, offset: Int, length: Int, lineSeparator: String): List { - - if (syntaxData == null) { - return emptyList() - } - - val content = text.substring(offset, offset + length) - val lines = content.split(lineSeparator.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() - - val styles = ArrayList() - - val separatorLength = lineSeparator.length - - var currentOffset = offset - - for (line in lines) { - val lineLength = line.length - val lineStyles = lineStylesFor(line, 0, lineLength) - - for (sr in lineStyles) { - sr.start += currentOffset - } - styles.addAll(lineStyles) - currentOffset += lineLength + separatorLength - } - - return styles - } - - fun lineStylesFor(lineText: String, lineOffset: Int, length: Int): List { - - val styles = ArrayList() - - var start = 0 - - // Check if line begins inside a multiline comment - val mlIndex = getBeginsInsideComment(lineOffset, lineText.length) - if (mlIndex > -1) { - // Line begins inside multiline comment; create the range - styles.add(StyleRange(lineOffset, mlIndex - lineOffset, COMMENT_COLOR, COMMENT_BACKGROUND)) - start = mlIndex - } - // Do punctuation, single-line comments, and keywords - while (start < length) { - // Check for multiline comments that begin inside this line - if (atMultiLineCommentStart(lineText, start)) { - // Determine where comment ends - var endComment = lineText.indexOf(syntaxData!!.multiLineCommentEnd!!, start) - - // If comment doesn't end on this line, extend range to end of - // line - if (endComment == -1) { - endComment = length - } else { - endComment += syntaxData!!.multiLineCommentEnd!!.length - } - styles.add(StyleRange(lineOffset + start, endComment - start, COMMENT_COLOR, COMMENT_BACKGROUND)) - - start = endComment - } else if (atStringStart(lineText, start)) { - // Determine where comment ends - var endString = lineText.indexOf(syntaxData!!.stringEnd!!, start + 1) - - // If string doesn't end on this line, extend range to end of - // line - if (endString == -1) { - endString = length - } else { - endString += syntaxData!!.stringEnd!!.length - } - styles.add(StyleRange(lineOffset + start, endString - start, STRING_COLOR, COMMENT_BACKGROUND)) - - start = endString - } else if (atSingleLineComment(lineText, start)) { - // line comments - - styles.add(StyleRange(lineOffset + start, length - start, COMMENT_COLOR, COMMENT_BACKGROUND)) - start = length - } else if (atVarnameReference(lineText, start)) { - // variable - // references - - val buf = StringBuilder() - var i = start + syntaxData!!.varnameReference!!.length - // Call any consecutive letters a word - while (i < length && Character.isLetter(lineText[i])) { - buf.append(lineText[i]) - i++ - } - - // See if the word is a variable - if (isDefinedVariable(buf.toString())) { - // It's a keyword; create the StyleRange - styles.add(StyleRange(lineOffset + start, i - start, REFERENCED_VAR_COLOR, null, SWT.BOLD)) - } - // Move the marker to the last char (the one that wasn't a - // letter) - // so it can be retested in the next iteration through the loop - start = i - } else if (syntaxData!!.isPunctuation(lineText[start])) { - // Add range for punctuation - styles.add(StyleRange(lineOffset + start, 1, PUNCTUATION_COLOR, null)) - ++start - } else if (Character.isLetter(lineText[start])) { - - val kwEnd = getKeywordEnd(lineText, start) - // is a keyword - - if (kwEnd > start) { - styles.add(StyleRange(lineOffset + start, kwEnd - start, KEYWORD_COLOR, null)) - } - - // Move the marker to the last char (the one that wasn't a - // letter) - // so it can be retested in the next iteration through the loop - start = Math.abs(kwEnd) - } else { - ++start // It's nothing we're interested in; advance the marker - }// Check for punctuation - } - - return styles - } - - companion object { - - private val COMMENT_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_DARK_GREEN) - private val REFERENCED_VAR_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_DARK_GREEN) - private val UNREFERENCED_VAR_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW) - private val COMMENT_BACKGROUND = Display.getCurrent().getSystemColor(SWT.COLOR_WHITE) - private val PUNCTUATION_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_BLACK) - private val KEYWORD_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_DARK_MAGENTA) - private val STRING_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_BLUE) - } -} diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/SyntaxData.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/SyntaxData.kt deleted file mode 100644 index 88e0f9dfd..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/SyntaxData.kt +++ /dev/null @@ -1,37 +0,0 @@ -package com.alibaba.smartfox.eclipse.ui.pmd - -/** - * This class contains information for syntax coloring and styling for an - * extension - */ -class SyntaxData(val extension: String) { - - var varnameReference: String? = null - var stringStart: String? = null - var stringEnd: String? = null - private var keywords: Collection? = null - private var punctuation: String? = null - var comment: String? = null - var multiLineCommentStart: String? = null - var multiLineCommentEnd: String? = null - - fun matches(otherExtension: String): Boolean { - return extension == otherExtension - } - - fun isKeyword(word: String): Boolean { - return keywords != null && keywords!!.contains(word) - } - - fun isPunctuation(ch: Char): Boolean { - return punctuation != null && punctuation!!.indexOf(ch) >= 0 - } - - fun setKeywords(keywords: Collection) { - this.keywords = keywords - } - - fun setPunctuation(thePunctuationChars: String) { - punctuation = thePunctuationChars - } -} diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/SyntaxManager.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/SyntaxManager.kt deleted file mode 100644 index 570e4bc28..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/SyntaxManager.kt +++ /dev/null @@ -1,94 +0,0 @@ -package com.alibaba.smartfox.eclipse.ui.pmd - -import org.eclipse.swt.custom.StyledText -import org.eclipse.swt.events.ModifyListener -import java.util.HashSet -import java.util.Hashtable -import java.util.MissingResourceException -import java.util.ResourceBundle -import java.util.StringTokenizer - -/** - * This class manages the syntax coloring and styling data - */ -object SyntaxManager { - - private val syntaxByExtension = Hashtable() - - fun adapt(codeField: StyledText, languageCode: String, oldListener: ModifyListener?): ModifyListener? { - - if (oldListener != null) { - codeField.removeModifyListener(oldListener) - } - - val sd = SyntaxManager.getSyntaxData(languageCode) ?: return null - - val blsl = BasicLineStyleListener(sd) - codeField.addLineStyleListener(blsl) - - val ml = ModifyListener { - blsl.refreshMultilineComments(codeField.text) - codeField.redraw() - } - codeField.addModifyListener(ml) - - return ml - } - - /** - * Gets the syntax data for an extension - */ - @Synchronized fun getSyntaxData(extension: String): SyntaxData? { - // Check in cache - var sd: SyntaxData? = syntaxByExtension[extension] - if (sd == null) { - // Not in cache; load it and put in cache - sd = loadSyntaxData(extension) - if (sd != null) { - syntaxByExtension.put(sd.extension, sd) - } - } - return sd - } - - /** - * Loads the syntax data for an extension - * @return SyntaxData - */ - private fun loadSyntaxData(filename: String): SyntaxData? { - var sd: SyntaxData? = null - try { - val rb = ResourceBundle.getBundle("/syntax/$filename") - sd = SyntaxData(filename) - - sd.stringStart = rb.getString("stringstart") - sd.stringEnd = rb.getString("stringend") - sd.multiLineCommentStart = rb.getString("multilinecommentstart") - sd.multiLineCommentEnd = rb.getString("multilinecommentend") - - // Load the keywords - val keywords = HashSet() - val st = StringTokenizer(rb.getString("keywords"), " ") - while (st.hasMoreTokens()) { - keywords.add(st.nextToken()) - } - sd.setKeywords(keywords) - - // Load the punctuation - sd.setPunctuation(rb.getString("punctuation")) - - if (rb.containsKey("comment")) { - sd.comment = rb.getString("comment") - } - - if (rb.containsKey("varnamedelimiter")) { - sd.varnameReference = rb.getString("varnamedelimiter") - } - - } catch (e: MissingResourceException) { - // Ignore - } - - return sd - } -} diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/util/CleanUps.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/util/CleanUps.kt deleted file mode 100644 index a5eba1dd4..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/util/CleanUps.kt +++ /dev/null @@ -1,361 +0,0 @@ -// ===================================================================== -// -// Copyright (C) 2012 - 2016, Philip Graf -// -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// which accompanies this distribution, and is available at -// http://www.eclipse.org/legal/epl-v10.html -// -// ===================================================================== -package com.alibaba.smartfox.eclipse.util - -import com.alibaba.smartfox.eclipse.SmartfoxActivator -import org.eclipse.core.filebuffers.FileBuffers -import org.eclipse.core.filebuffers.ITextFileBuffer -import org.eclipse.core.filebuffers.LocationKind -import org.eclipse.core.resources.IFile -import org.eclipse.core.runtime.Assert -import org.eclipse.core.runtime.CoreException -import org.eclipse.core.runtime.IProgressMonitor -import org.eclipse.core.runtime.IStatus -import org.eclipse.core.runtime.NullProgressMonitor -import org.eclipse.core.runtime.Status -import org.eclipse.jdt.core.ICompilationUnit -import org.eclipse.jdt.core.IJavaProject -import org.eclipse.jdt.core.JavaCore -import org.eclipse.jdt.core.dom.CompilationUnit -import org.eclipse.jdt.internal.corext.fix.CleanUpConstants -import org.eclipse.jdt.internal.corext.fix.CleanUpRefactoring -import org.eclipse.jdt.internal.corext.fix.FixMessages -import org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser -import org.eclipse.jdt.internal.ui.JavaPlugin -import org.eclipse.jdt.internal.ui.actions.ActionUtil -import org.eclipse.jdt.internal.ui.fix.MapCleanUpOptions -import org.eclipse.jdt.ui.SharedASTProvider -import org.eclipse.jdt.ui.cleanup.CleanUpContext -import org.eclipse.jdt.ui.cleanup.CleanUpOptions -import org.eclipse.jdt.ui.cleanup.ICleanUp -import org.eclipse.jface.text.BadLocationException -import org.eclipse.jface.text.IDocument -import org.eclipse.jface.text.IDocumentExtension4 -import org.eclipse.jface.window.Window -import org.eclipse.ltk.core.refactoring.Change -import org.eclipse.ltk.core.refactoring.CompositeChange -import org.eclipse.ltk.core.refactoring.IRefactoringCoreStatusCodes -import org.eclipse.ltk.core.refactoring.NullChange -import org.eclipse.ltk.core.refactoring.PerformChangeOperation -import org.eclipse.ltk.core.refactoring.RefactoringCore -import org.eclipse.ltk.core.refactoring.RefactoringStatus -import org.eclipse.ltk.core.refactoring.TextFileChange -import org.eclipse.ltk.ui.refactoring.RefactoringUI -import org.eclipse.text.edits.MalformedTreeException -import org.eclipse.text.edits.TextEdit -import org.eclipse.text.edits.UndoEdit -import org.eclipse.ui.PlatformUI -import java.util.ArrayList -import java.util.HashMap -import java.util.LinkedList - -/** - * - * - * @author caikang - * @date 2017/06/15 - */ -object CleanUps { - - private val WARNING_VALUE = "warning" - private val ERROR_VALUE = "error" - - val cleanUpSettings = mapOf(CleanUpConstants.ADD_MISSING_ANNOTATIONS to CleanUpOptions.TRUE, - CleanUpConstants.CONTROL_STATMENTS_USE_BLOCKS_ALWAYS to CleanUpOptions.TRUE, - CleanUpConstants.ADD_MISSING_ANNOTATIONS_OVERRIDE to CleanUpOptions.TRUE, - CleanUpConstants.CONTROL_STATEMENTS_USE_BLOCKS to CleanUpOptions.TRUE, - CleanUpConstants.ADD_MISSING_ANNOTATIONS_OVERRIDE_FOR_INTERFACE_METHOD_IMPLEMENTATION to - CleanUpOptions.TRUE) - - fun fix(file: IFile, monitor: IProgressMonitor) { - val compilationUnit = JavaCore.createCompilationUnitFrom(file) ?: return - doCleanUp(compilationUnit, monitor) - } - - @Throws(CoreException::class) fun doCleanUp(unit: ICompilationUnit, monitor: IProgressMonitor) { - - monitor.beginTask("Fix", IProgressMonitor.UNKNOWN) - - if (!ActionUtil.isOnBuildPath(unit)) return - val result = CompositeChange(FixMessages.CleanUpPostSaveListener_SaveAction_ChangeName) - val undoEdits = LinkedList() - val oldFileValue = unit.resource.modificationStamp - val oldDocValue = getDocumentStamp(unit.resource as IFile, monitor) - val manager = RefactoringCore.getUndoManager() - var success = false - - try { - manager.aboutToPerformChange(result) - success = doCleanUp(unit, monitor, result, undoEdits) - } finally { - manager.changePerformed(result, success) - } - - if (undoEdits.size > 0) { - val undoEditArray = undoEdits.toTypedArray() - val undo = CleanUpSaveUndo(result.name, unit.resource as IFile, undoEditArray, oldDocValue, oldFileValue) - undo.initializeValidationData(NullProgressMonitor()) - manager.addUndo(result.name, undo) - } - } - - @Throws(CoreException::class) private fun getDocumentStamp(file: IFile, monitor: IProgressMonitor): Long { - val manager = FileBuffers.getTextFileBufferManager() - val path = file.fullPath - - monitor.beginTask("", 2) - - var buffer: ITextFileBuffer? = null - try { - manager.connect(path, LocationKind.IFILE, monitor) - buffer = manager.getTextFileBuffer(path, LocationKind.IFILE) - val document = buffer!!.document - - if (document is IDocumentExtension4) { - return document.modificationStamp - } else { - return file.modificationStamp - } - } finally { - if (buffer != null) manager.disconnect(path, LocationKind.IFILE, monitor) - monitor.done() - } - } - - private fun doCleanUp(unit: ICompilationUnit, monitor: IProgressMonitor, result: CompositeChange, - undoEdits: LinkedList): Boolean { - val cleanUps = JavaPlugin.getDefault().cleanUpRegistry.createCleanUps( - setOf("org.eclipse.jdt.ui.cleanup.java50", "org.eclipse.jdt.ui.cleanup.control_statements")) - val preCondition = RefactoringStatus() - val postCondition = RefactoringStatus() - cleanUps.forEach { cleanUp -> - cleanUp.setOptions(MapCleanUpOptions(cleanUpSettings)) - - preCondition.merge(cleanUp.checkPreConditions(unit.javaProject, arrayOf(unit), monitor)) - - val options = HashMap(cleanUp.requirements.compilerOptions ?: emptyMap()) - - var ast = CleanUps.createAst(unit, options, monitor) - if (cleanUp.requirements.requiresAST()) { - ast = createAst(unit, options, monitor) - } - - val context = CleanUpContext(unit, ast) - - val undoneCleanUps = ArrayList() - val change = CleanUpRefactoring.calculateChange(context, arrayOf(cleanUp), undoneCleanUps, null) - - postCondition.merge(cleanUp.checkPostConditions(monitor)) - if (showStatus(postCondition) != Window.OK) { - return@doCleanUp false - } - - if (change == null) { - return@forEach - } - result.add(change) - - change.initializeValidationData(NullProgressMonitor()) - - val performChangeOperation = PerformChangeOperation(change) - performChangeOperation.setSchedulingRule(unit.schedulingRule) - performChangeOperation.run(monitor) - performChangeOperation.undoChange - undoEdits.addFirst(change.undoEdit) - } - - return true - } - - private fun showStatus(status: RefactoringStatus): Int { - if (!status.hasError()) return Window.OK - - val shell = PlatformUI.getWorkbench().activeWorkbenchWindow.shell - - val dialog = RefactoringUI.createRefactoringStatusDialog(status, shell, "", false) - return dialog.open() - } - - private fun createAst(unit: ICompilationUnit, cleanUpOptions: Map, - monitor: IProgressMonitor): CompilationUnit { - val project = unit.javaProject - if (compatibleOptions(project, cleanUpOptions)) { - val ast = SharedASTProvider.getAST(unit, SharedASTProvider.WAIT_NO, monitor) - if (ast != null) return ast - } - - val parser = CleanUpRefactoring.createCleanUpASTParser() - parser.setSource(unit) - - val compilerOptions = RefactoringASTParser.getCompilerOptions(unit.javaProject) - compilerOptions.putAll(cleanUpOptions) - parser.setCompilerOptions(compilerOptions) - - return parser.createAST(monitor) as CompilationUnit - } - - private fun compatibleOptions(project: IJavaProject, cleanUpOptions: Map): Boolean { - if (cleanUpOptions.isEmpty()) { - return true - } - - val projectOptions = project.getOptions(true) - - return !cleanUpOptions.keys.any { - val projectOption = projectOptions[it]?.toString() - val cleanUpOption = cleanUpOptions[it]?.toString() - !strongerEquals(projectOption, cleanUpOption) - } - } - - private fun strongerEquals(projectOption: String?, cleanUpOption: String?): Boolean { - if (projectOption == null) return false - - if (ERROR_VALUE == cleanUpOption) { - return ERROR_VALUE == projectOption - } else if (WARNING_VALUE == cleanUpOption) { - return ERROR_VALUE == projectOption || WARNING_VALUE == projectOption - } - - return false - } - - private class CleanUpSaveUndo(name: String, private val fFile: IFile, private val fUndos: Array, - private val fDocumentStamp: Long, private val fFileStamp: Long) : TextFileChange(name, - fFile) { - - init { - Assert.isNotNull(fUndos) - } - - public override fun needsSaving(): Boolean { - return true - } - - @Throws(CoreException::class) override fun perform(monitor: IProgressMonitor?): Change { - val pm = monitor ?: NullProgressMonitor() - if (isValid(pm).hasFatalError()) return NullChange() - - val manager = FileBuffers.getTextFileBufferManager() - pm.beginTask("", 2) - var buffer: ITextFileBuffer? = null - - try { - manager.connect(fFile.fullPath, LocationKind.IFILE, pm) - buffer = manager.getTextFileBuffer(fFile.fullPath, LocationKind.IFILE) - - val document = buffer!!.document - val oldFileValue = fFile.modificationStamp - val undoEditCollector = LinkedList() - val oldDocValue = LongArray(1) - val setContentStampSuccess = booleanArrayOf(false) - - if (!buffer.isSynchronizationContextRequested) { - performEdit(document, oldFileValue, undoEditCollector, oldDocValue, setContentStampSuccess) - - } else { - val fileBufferManager = FileBuffers.getTextFileBufferManager() - - class UIRunnable : Runnable { - var fDone: Boolean = false - var fException: Exception? = null - - override fun run() { - synchronized(this) { - try { - performEdit(document, oldFileValue, undoEditCollector, oldDocValue, - setContentStampSuccess) - } catch (e: BadLocationException) { - fException = e - } catch (e: MalformedTreeException) { - fException = e - } catch (e: CoreException) { - fException = e - } finally { - fDone = true - (this as Object).notifyAll() - } - } - } - } - - val runnable = UIRunnable() - - synchronized(runnable) { - fileBufferManager.execute(runnable) - while (!runnable.fDone) { - try { - (runnable as Object).wait(500) - } catch (x: InterruptedException) { - } - - } - } - - if (runnable.fException != null) { - if (runnable.fException is BadLocationException) { - throw runnable.fException as BadLocationException - } else if (runnable.fException is MalformedTreeException) { - throw runnable.fException as MalformedTreeException - } else if (runnable.fException is CoreException) { - throw runnable.fException as CoreException - } - } - } - - buffer.commit(pm, false) - if (!setContentStampSuccess[0]) { - fFile.revertModificationStamp(fFileStamp) - } - - return CleanUpSaveUndo(name, fFile, undoEditCollector.toTypedArray(), oldDocValue[0], oldFileValue) - } catch (e: BadLocationException) { - throw wrapBadLocationException(e) - } finally { - if (buffer != null) manager.disconnect(fFile.fullPath, LocationKind.IFILE, pm) - } - } - - @Throws(MalformedTreeException::class, BadLocationException::class, - CoreException::class) private fun performEdit(document: IDocument, oldFileValue: Long, - editCollector: LinkedList, - oldDocValue: LongArray, - setContentStampSuccess: BooleanArray) { - if (document is IDocumentExtension4) { - oldDocValue[0] = document.modificationStamp - } else { - oldDocValue[0] = oldFileValue - } - - // perform the changes - fUndos.map { it.apply(document, TextEdit.CREATE_UNDO) }.forEach { editCollector.addFirst(it) } - - if (document is IDocumentExtension4 && fDocumentStamp != IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP) { - try { - document.replace(0, 0, "", fDocumentStamp) - setContentStampSuccess[0] = true - } catch (e: BadLocationException) { - throw wrapBadLocationException(e) - } - - } - } - } - - private fun wrapBadLocationException(e: BadLocationException): CoreException { - var message: String? = e.message - if (message == null) message = "BadLocationException" - return CoreException( - Status(IStatus.ERROR, SmartfoxActivator.PLUGIN_ID, IRefactoringCoreStatusCodes.BAD_LOCATION, message, - e)) - } - -} \ No newline at end of file diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/util/MarkerUtil.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/util/MarkerUtil.kt deleted file mode 100644 index 4c021bb98..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/util/MarkerUtil.kt +++ /dev/null @@ -1,135 +0,0 @@ -// ===================================================================== -// -// Copyright (C) 2012 - 2016, Philip Graf -// -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// which accompanies this distribution, and is available at -// http://www.eclipse.org/legal/epl-v10.html -// -// ===================================================================== -package com.alibaba.smartfox.eclipse.util - -import com.alibaba.smartfox.eclipse.QuickFixGenerator -import com.alibaba.smartfox.eclipse.SmartfoxActivator -import com.google.common.io.Files -import net.sourceforge.pmd.Rule -import net.sourceforge.pmd.RulePriority -import net.sourceforge.pmd.RuleViolation -import org.eclipse.core.resources.IFile -import org.eclipse.core.resources.IMarker -import org.eclipse.core.resources.IProject -import org.eclipse.core.resources.IResource -import org.eclipse.core.runtime.CoreException -import org.eclipse.jface.text.BadLocationException -import org.eclipse.jface.text.Document -import org.eclipse.ui.IMarkerResolution -import java.nio.charset.Charset - -/** - * @author caikang - * @date 2017/06/08 - */ -object MarkerUtil { - - private val PMD_TAB_SIZE = 8 - - private val MARKER_TYPE = "${SmartfoxActivator.PLUGIN_ID}.p3cMarker" - - @Throws(CoreException::class) - fun removeAllMarkers(file: IFile) { - try { - if (file.exists()) { - file.deleteMarkers(MARKER_TYPE, true, IResource.DEPTH_ZERO) - } - } catch (e: Exception) { - SmartfoxActivator.instance.logError(e.message ?: "", e) - } - } - - @Throws(CoreException::class) - fun removeAllMarkers(project: IProject) { - project.deleteMarkers(MARKER_TYPE, true, IResource.DEPTH_INFINITE) - } - - @Throws(CoreException::class) - fun addMarker(file: IFile, violation: RuleViolation): IMarker { - val marker = file.createMarker(MARKER_TYPE) - marker.setAttribute(IMarker.MESSAGE, violation.description) - val severity = when (violation.rule.priority) { - RulePriority.HIGH -> IMarker.SEVERITY_ERROR - RulePriority.MEDIUM_HIGH -> IMarker.SEVERITY_WARNING - else -> IMarker.SEVERITY_INFO - } - marker.setRule(violation.rule.name) - marker.setAttribute(IMarker.SEVERITY, severity) - marker.setAttribute(IMarker.LINE_NUMBER, Math.max(violation.beginLine, 0)) - val range = getAbsoluteRange(file, violation) - val start = Math.max(range.start, 0) - marker.setAttribute(IMarker.CHAR_START, start) - val end = Math.max(range.end, 0) - marker.setAttribute(IMarker.CHAR_END, end) - return marker - } - - - fun getAbsoluteRange(file: IFile, violation: RuleViolation): Range { - val content = Files.toString(file.rawLocation.toFile(), Charset.forName(file.charset)) - try { - return calculateAbsoluteRange(content, violation) - } catch (e: BadLocationException) { - return Range(0, 0) - } - } - - @Throws(BadLocationException::class) private fun calculateAbsoluteRange(content: String, - violation: RuleViolation): Range { - val document = Document(content) - - // violation line and column start at one, the marker's start and end positions at zero - val start = getAbsolutePosition(content, document.getLineOffset(violation.beginLine - 1), violation.beginColumn) - val end = getAbsolutePosition(content, document.getLineOffset(violation.endLine - 1), violation.endColumn) - - // for some rules PMD creates violations with the end position before the start position - val range = if (start <= end) { - Range(start - 1, end) - } else { - Range(end - 1, start) - } - - return range - } - - private fun getAbsolutePosition(content: String, lineOffset: Int, pmdCharOffset: Int): Int { - var pmdCharCounter = 0 - var absoluteOffset = lineOffset - while (pmdCharCounter < pmdCharOffset) { - if (absoluteOffset < content.length) { - val c = content[absoluteOffset] - if (c == '\t') { - pmdCharCounter = (pmdCharCounter / PMD_TAB_SIZE + 1) * PMD_TAB_SIZE - } else { - pmdCharCounter++ - } - } else { - break - } - absoluteOffset++ - } - return absoluteOffset - } -} - -fun IMarker.setRule(rule: String) { - this.setAttribute("rule", rule) -} - -fun IMarker.getRule(): Rule { - return SmartfoxActivator.instance.getRule(this.getAttribute("rule") as String) -} - -fun IMarker.getResolution(): IMarkerResolution? { - return QuickFixGenerator.quickFixes[getRule().name] -} - -data class Range(val start: Int, val end: Int) diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/messages/P3cBundle.xml b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/messages/P3cBundle.xml deleted file mode 100644 index 755afb5ba..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/messages/P3cBundle.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - 阿里编码规约扫描 - - 切换语言至英文(English) - 切换语言至中文 - 切换到English成功,是否重启 - 切换到中文成功,是否重启 - - - - - - - - - - - \ No newline at end of file diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/messages/P3cBundle_en.xml b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/messages/P3cBundle_en.xml deleted file mode 100644 index 091d2a743..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/messages/P3cBundle_en.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - Alibaba Coding Guidelines Analyze - Switch language to English - Switch language to Chinese - - Switch language to English success,restart? - Switch language to Chinese success,restart? - - - - - - - - - - - \ No newline at end of file diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/rulesets/java/ali-pmd.xml b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/rulesets/java/ali-pmd.xml deleted file mode 100644 index 3ae5d7360..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/rulesets/java/ali-pmd.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/rulesets/java/ali-ruleOnEclipse.xml b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/rulesets/java/ali-ruleOnEclipse.xml deleted file mode 100644 index e25eb51ce..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/rulesets/java/ali-ruleOnEclipse.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - rule.standalone.MissingOverrideAnnotationRule.desc - 1 - - - - - - - 1 - - - rule.standalone.AvoidUseDeprecationRule.desc - 2 - - - - rule.standalone.MapOrSetKeyShouldOverrideHashCodeEqualsRule.desc - 2 - - diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/syntax/java.properties b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/syntax/java.properties deleted file mode 100644 index f1c6ed499..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/syntax/java.properties +++ /dev/null @@ -1,8 +0,0 @@ -# This file contains the syntax data for .java files -comment=// -stringstart=" -stringend=" -multilinecommentstart=/* -multilinecommentend=*/ -punctuation=(){};:?<>=+-*/&|~!%.[] -keywords=abstract assert boolean break byte case catch char class const continue do double else enum extends false final finally for if implements import int interface native new null package protected public private return static strictfp super switch synchronized this throws true try void volatile while diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.updatesite/category.xml b/eclipse-plugin/com.alibaba.smartfox.eclipse.updatesite/category.xml deleted file mode 100644 index 15c89a264..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.updatesite/category.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - Alibaba Java Coding Guidelines - - - - - - diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.updatesite/pom.xml b/eclipse-plugin/com.alibaba.smartfox.eclipse.updatesite/pom.xml deleted file mode 100644 index 91a5011e1..000000000 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.updatesite/pom.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - 4.0.0 - - com.alibaba.smartfox.eclipse - smartfox-eclipse - 2.0.1-SNAPSHOT - - com.alibaba.smartfox.eclipse.updatesite - eclipse-repository - 2017 - diff --git a/eclipse-plugin/doc/images/analyze_result.png b/eclipse-plugin/doc/images/analyze_result.png deleted file mode 100644 index aad166b7b..000000000 Binary files a/eclipse-plugin/doc/images/analyze_result.png and /dev/null differ diff --git a/eclipse-plugin/doc/images/eclipse_analyze.png b/eclipse-plugin/doc/images/eclipse_analyze.png deleted file mode 100644 index 92e933c2c..000000000 Binary files a/eclipse-plugin/doc/images/eclipse_analyze.png and /dev/null differ diff --git a/eclipse-plugin/doc/images/eclipse_switch_language.png b/eclipse-plugin/doc/images/eclipse_switch_language.png deleted file mode 100644 index e8f21848a..000000000 Binary files a/eclipse-plugin/doc/images/eclipse_switch_language.png and /dev/null differ diff --git a/eclipse-plugin/doc/images/install.png b/eclipse-plugin/doc/images/install.png deleted file mode 100644 index 5a60033c8..000000000 Binary files a/eclipse-plugin/doc/images/install.png and /dev/null differ diff --git a/eclipse-plugin/pom.xml b/eclipse-plugin/pom.xml deleted file mode 100644 index b93603c17..000000000 --- a/eclipse-plugin/pom.xml +++ /dev/null @@ -1,198 +0,0 @@ - - - 4.0.0 - com.alibaba.smartfox.eclipse - smartfox-eclipse - 2.0.1-SNAPSHOT - pom - 2017 - - 1.0.0 - ${tycho.version} - http://download.eclipse.org/releases/neon - UTF-8 - http://download.eclipse.org/tools/ajdt/46/dev/update - 1.3.30 - juno - - - com.alibaba.smartfox.eclipse.plugin - com.alibaba.smartfox.eclipse.feature - com.alibaba.smartfox.eclipse.updatesite - - - - junit - junit - 4.11 - test - - - - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - ${kotlin.version} - compile - - - - - - juno - p2 - http://mirrors.ustc.edu.cn/eclipse/releases/juno/ - - - sonatype-nexus-snapshots - Sonatype Nexus Snapshots - https://oss.sonatype.org/content/repositories/snapshots - - false - - - true - - - - - - - org.eclipse.tycho - tycho-maven-plugin - ${tycho.version} - true - - - org.eclipse.tycho - target-platform-configuration - - - - linux - gtk - x86 - - - linux - gtk - x86_64 - - - win32 - win32 - x86 - - - win32 - win32 - x86_64 - - - macosx - cocoa - x86_64 - - - - - - - - - - org.eclipse.tycho - target-platform-configuration - ${tycho.version} - - - org.eclipse.tycho - tycho-compiler-plugin - ${tycho.version} - - 1.8 - - - - UTF-8 - - -err:-forbidden - - - - org.codehaus.mojo - aspectj-maven-plugin - ${aspectj.plugin.version} - - - org.aspectj - aspectjtools - ${aspectj.version} - - - - - org.eclipse.tycho - tycho-packaging-plugin - ${tycho.version} - - - org.eclipse.tycho - tycho-surefire-plugin - ${tycho.version} - - true - - - - org.eclipse.tycho - tycho-source-plugin - ${tycho.version} - - false - - - - org.eclipse.tycho - tycho-p2-director-plugin - ${tycho.version} - - - org.eclipse.tycho - tycho-p2-repository-plugin - ${tycho.version} - - smartfox-eclipse-plugin - - - - org.eclipse.tycho.extras - tycho-source-feature-plugin - ${tycho-extras.version} - - - org.eclipse.tycho.extras - tycho-custom-bundle-plugin - ${tycho-extras.version} - - - org.eclipse.tycho - tycho-p2-plugin - ${tycho.version} - - warn - none - - - http://download.eclipse.org/eclipse/updates/4.4 - - - - - - - - diff --git a/idea-plugin/.gitignore b/idea-plugin/.gitignore index b0bfb71a9..4ef3a798f 100644 --- a/idea-plugin/.gitignore +++ b/idea-plugin/.gitignore @@ -70,7 +70,6 @@ configuration/** # sass gitignore# .sass-cache -.idea # tcc_coverage coverage.ec @@ -81,7 +80,6 @@ config.client.* temp/ *.pid -*.orig hsf.configuration/ diff --git a/idea-plugin/README.md b/idea-plugin/README.md index 488e5d617..9a2b10e13 100644 --- a/idea-plugin/README.md +++ b/idea-plugin/README.md @@ -1,8 +1,8 @@ # Idea Plugin --- ## Prepare -- Project JDK: 1.7+ -- Gradle: 3.0+(Require JDK1.8+ for gradle) +- Project JDK: 11 +- Gradle: 7.3(Require JDK17 for gradle) ## Build ``` @@ -21,7 +21,7 @@ cd p3c-idea ## Use p3c-common as your plugin dependency ```groovy -compile 'com.alibaba.p3c.idea:p3c-common:1.0.0' +compile 'com.xenoamess.p3c.idea:p3c-common:2.2.4.0x-SNAPSHOT' ``` ## [中文使用手册](README_cn.md) ## Install @@ -60,6 +60,23 @@ compile 'com.alibaba.p3c.idea:p3c-common:1.0.0' We use the idea standard Inspection Results to show our violations. ![Result](doc/images/inspection_result.png) + +Results are grouped by tags, which include Blocker,Critical,Major,Warning,Weak Warning. + +Blocker, Critical and Major will remain sync with alibaba official version, and will not be changed freely, unless especially declared. + +When I see some reasonable third party rules in Community I might add them to Warning or Weak Warning. + +Usually, if a third party rule can be followed in every situation, then it is tagged Warning. + +Otherwise, if it cannot be followed in some special cases, then it will be tagged Weak Warning. + +If you want to use pmd-maven-plugin for auto-analyze and assure, + +You should set `3` for having same behavior than alibaba official version. + +See example/use-case in `p3c-pmd/pom.xml` + We can also analyze file which is modified before vcs checkin. @@ -76,3 +93,281 @@ compile 'com.alibaba.p3c.idea:p3c-common:1.0.0' ![Switch language](doc/images/normal_view.png) +## Configuration mechanism +### Configuration file path + +For p3c-idea-plugin, configuration file should be put at "$your_project_path/p3c_config.x8l". + +For p3c-pmd for maven, configuration file should be put at "$the_dir_you_run_mvn/p3c_config.x8l". + +Usually this two position be pointed at a same file. + +### File format + +File format be [x8l](https://github.com/cyanpotion/x8l). +Yep I write it. + +### File analyze + +For example at [cyan_potion](https://github.com/cyanpotion/cyan_potionp3c_config.x8l) , +we learn about how it works. + +Firstly p3c_config.x8l be at "$your_project_path/p3c_config.x8l". + +``` + + + + + DAOImpl& + GLFW& + URL& + URI& + XInput& + PosX& + PosY& + AWT& + XY& + drawBoxTC& + FPS& + ID& + lastX& + lastY& + > + > + + + Hbase& + HBase& + ID& + ConcurrentHashMap& + GLFW& + URL& + URI& + JXInput& + SettingFileParser_ + > + > + > + + PackageNamingRule& + AbstractClassShouldStartWithAbstractNamingRule& + ThreadPoolCreationRule& + MethodTooLongRule& + > + + Console + > + + com.xenoamess.cyan_potion.base.steam + > + + EnumConstantsMustHaveCommentRule> + EnumConstantsMustHaveCommentRule> + EnumConstantsMustHaveCommentRule> + EnumConstantsMustHaveCommentRule> + EnumConstantsMustHaveCommentRule> + EnumConstantsMustHaveCommentRule> + + UndefineMagicConstantRule> + + AvoidUseDeprecationRule> + + AvoidUseDeprecationRule> + AvoidUseDeprecationRule> + AvoidUseDeprecationRule> + + LowerCamelCaseVariableNamingRule&AvoidUseDeprecationRule> + + ConstantFieldShouldBeUpperCaseRule> + > +> +``` + +Root node's name MUST be "com.alibaba.p3c.pmd.config". + +Attribute "version=0.0.1" is version of configuration file. +It is actually not used yet but stongly suggested force it here, +as for breaking updates. + +For this repo, we opened trim for x8l file, means all readed String will be trimed first. + +For example, + +``` + + Console + > +``` + +see the TextNode + +``` + + Console + +``` + +It will be trimmed to `Console` before used. + +There can be 4 children nodes under node com.alibaba.p3c.pmd.config, as shown below. + +### rule_config + +Node rule_config contains detailed settings for some rules. + +For example, LowerCamelCaseVariableNamingRule's attribute WHITE_LIST. + +This attribute need a String List, +then we read several TextNodes under a ContentNode as a String List. + +### rule_blacklist + +Node rule_blacklist contains global settings for a repo, +means ban rules in this repo globally. + +For example, if rule_blacklist contains PackageNamingRule, +then means in this repo we will not detect PackageNamingRule. + +Rule class name in rule_blacklist CAN be SimpleName OR CanonicalName. + +### class_blacklist + +Node class_blacklist contains global settings for a repo, +means ban classes in this repo globally. + +For example, if class_blacklist contains Console, +then means in this repo we will not detect anything for all classes whose name be Console. + +BE ATTENTION, according to PMD interface reason, +class names in class_blacklist must be SimpleName. + +### package_blacklist + +Node package_blacklist contains global settings for a repo, +means ban packages in this repo globally. + +For example, if package_blacklist contains `com.xenoamess`, +then means in this repo we will not detect anything for all classes whose package under `com.xenoamess`. + +BE ATTENTION, it will also ban packages under `com.xenoamess`, like `com.xenoamess.cyan_potion` + +### rule_class_pair_blacklist + +Node rule_class_pair_blacklist contains settings for class/rule pairs, +means ban some rules in this repo for some classes. + +For example, if rule_class_pair_blacklist contains +`LowerCamelCaseVariableNamingRule&AvoidUseDeprecationRule>` +, +then means in this repo we will not detect LowerCamelCaseVariableNamingRule nor AvoidUseDeprecationRule, +for all classes whose name be GameInputManager. + + +Rule class name in rule_class_pair_blacklist CAN be SimpleName OR CanonicalName. + +BE ATTENTION, according to PMD interface reason, +class names in rule_class_pair_blacklist must be SimpleName. + +### For the X8L Haters + +If you really hate x8l you can use json configuration files. + +```json +{ + "com.alibaba.p3c.pmd.config": { + "_attributes": { + "version": "0.0.1" + }, + "rule_config": { + "LowerCamelCaseVariableNamingRule": { + "WHITE_LIST": [ + "DAOImpl", + "GLFW", + "URL", + "URI", + "XInput", + "PosX", + "PosY", + "AWT", + "XY", + "drawBoxTC", + "FPS", + "ID", + "lastX", + "lastY" + ] + }, + "ClassNamingShouldBeCamelRule": { + "CLASS_NAMING_WHITE_LIST": [ + "Hbase", + "HBase", + "ID", + "ConcurrentHashMap", + "GLFW", + "URL", + "URI", + "JXInput", + "SettingFileParser_" + ] + } + }, + "rule_blacklist": [ + "PackageNamingRule", + "AbstractClassShouldStartWithAbstractNamingRule", + "ThreadPoolCreationRule", + "MethodTooLongRule" + ], + "class_blacklist": [ + "Console" + ], + "package_blacklist": [ + "com.xenoamess.cyan_potion.base.steam" + ], + "rule_class_pair_blacklist": { + "JamepadGamepadKeyEnum": [ + "EnumConstantsMustHaveCommentRule" + ], + "JXInputGamepadKeyEnum": [ + "EnumConstantsMustHaveCommentRule" + ], + "KeyActionEnum": [ + "EnumConstantsMustHaveCommentRule" + ], + "KeyboardKeyEnum": [ + "EnumConstantsMustHaveCommentRule" + ], + "CodePluginPosition": [ + "EnumConstantsMustHaveCommentRule" + ], + "ShapeRelation": [ + "EnumConstantsMustHaveCommentRule" + ], + "WaveData": [ + "UndefineMagicConstantRule" + ], + "FileUtils": [ + "AvoidUseDeprecationRule" + ], + "Font": [ + "AvoidUseDeprecationRule" + ], + "Keymap": [ + "AvoidUseDeprecationRule" + ], + "WorldForDemo": [ + "AvoidUseDeprecationRule" + ], + "GameInputManager": [ + "LowerCamelCaseVariableNamingRule", + "AvoidUseDeprecationRule" + ], + "Colors": [ + "ConstantFieldShouldBeUpperCaseRule" + ] + } + } +} +``` + +name it p3c_config.json diff --git a/idea-plugin/README_cn.md b/idea-plugin/README_cn.md index 90ab1feb9..6700506cc 100644 --- a/idea-plugin/README_cn.md +++ b/idea-plugin/README_cn.md @@ -4,11 +4,11 @@ ### 通过Jetbrains官方仓库安装 1. 打开 Settings >> Plugins >> Browse repositories... - ![](https://gw.alicdn.com/tfscom/TB1Qn83ifBNTKJjy1zdXXaScpXa.png) +![](https://gw.alicdn.com/tfscom/TB1Qn83ifBNTKJjy1zdXXaScpXa.png) 2. 在搜索框输入alibaba即可看到Alibaba Java Code Guidelines插件,点击Install进行安装,然后重启IDE生效 `注意:因为插件zip包托管在Jetbrains官方CDN上,所以是从国外的服务器进行下载,可能会出现超时的情况` - ![](https://gw.alicdn.com/tfscom/TB1vcGbmYsTMeJjy1zcXXXAgXXa.png) +![](https://gw.alicdn.com/tfscom/TB1vcGbmYsTMeJjy1zcXXXAgXXa.png) ### 通过下载安装包进行安装 1. 打开[插件](https://plugins.jetbrains.com/plugin/10046-alibaba-java-coding-guidelines)页面 @@ -17,7 +17,7 @@ 2. Settings >> Plugins >> Install plugin from disk...,选择刚刚下载的zip包安装,然后重启IDE - ![](https://gw.alicdn.com/tfscom/TB1WFsKiqigSKJjSsppXXabnpXa.png) +![](https://gw.alicdn.com/tfscom/TB1WFsKiqigSKJjSsppXXabnpXa.png) ### 注意 @@ -30,11 +30,11 @@ 1. 修改字体——Appearance&Behavior -> Appearance -> UI Options -> Name 里面设置成中文字体——如微软雅黑(microsoft yahei light)、文泉驿(linux) - ![](https://gw.alicdn.com/tfscom/TB14wTmm3oQMeJjy0FoXXcShVXa.png) +![](https://gw.alicdn.com/tfscom/TB14wTmm3oQMeJjy0FoXXcShVXa.png) 2. Switch Language to English and restart. - ![](https://gw.alicdn.com/tfscom/TB1Z6u1mYsTMeJjSszhXXcGCFXa.png) +![](https://gw.alicdn.com/tfscom/TB1Z6u1mYsTMeJjSszhXXcGCFXa.png) ## 插件使用 @@ -49,24 +49,25 @@

检测结果高亮提示,并且鼠标放上去会弹出提示信息。

- ![](https://gw.alicdn.com/tfscom/TB17wt3mYsTMeJjSszdXXcEupXa.png) +![](https://gw.alicdn.com/tfscom/TB17wt3mYsTMeJjSszdXXcEupXa.png) - ![](https://gw.alicdn.com/tfscom/TB1Rq85ifNNTKJjSspkXXaeWFXa.png) +![](https://gw.alicdn.com/tfscom/TB1Rq85ifNNTKJjSspkXXaeWFXa.png) #### Intention QuickFix功能 Alt+Enter键可呼出Intention菜单,不同的规则会提示不同信息的Quick Fix按钮 - ![](https://gw.alicdn.com/tfscom/TB1twLMsOAKL1JjSZFoXXagCFXa.png) +![](https://gw.alicdn.com/tfscom/TB1twLMsOAKL1JjSZFoXXagCFXa.png) #### 关闭实时检测 在某些情况下,我们不希望对代码提示违规信息,比如我们在阅读Github开源项目代码的时候,如果界面出现一堆红色、黄色的提示,此时心里肯定是飘过一万只草泥马。这个时候我们可以通过Inspection的设置关闭实时检测功能。 1. 通过右键快速关闭(打开)所有规则的实时检测功能 - ![](https://gw.alicdn.com/tfscom/TB1dBbDe_1z01JjSZFCXXXY.XXa.png) +![](https://gw.alicdn.com/tfscom/TB1dBbDe_1z01JjSZFCXXXY.XXa.png) + 2. 通过Settings >> Editor >> Inspections 进行手动设置 - ![](https://gw.alicdn.com/tfscom/TB1zhCBsiFTMKJjSZFAXXckJpXa.png) +![](https://gw.alicdn.com/tfscom/TB1zhCBsiFTMKJjSZFAXXckJpXa.png) 也可以关闭某条规则的实时检测功能或者修改提示级别。 @@ -77,43 +78,319 @@ Alt+Enter键可呼出Intention菜单,不同的规则会提示不同信息的Qu #### 触发扫描 在当前编辑的文件中点击右键,可以在弹出的菜单中触发对该文件的检测。 - ![](https://gw.alicdn.com/tfscom/TB1Wj49mYsTMeJjSszdXXcEupXa.png) +![](https://gw.alicdn.com/tfscom/TB1Wj49mYsTMeJjSszdXXcEupXa.png) 在左侧的Project目录树种点击右键,可以触发对整个工程或者选择的某个目录、文件进行检测。 - ![](https://gw.alicdn.com/tfscom/TB1h_XciWmgSKJjSspiXXXyJFXa.png) +![](https://gw.alicdn.com/tfscom/TB1h_XciWmgSKJjSspiXXXyJFXa.png) 如果您打开了IDE的Toolbar,也可以通过Toolbar中的按钮来触发检测,目前Toolbar的按钮触发的检测范围与您IDE当时的焦点有关,如当前编辑的文件或者是Project目录树选中的项,是不是感觉与右键菜单的检测范围类似呢。 - ![](https://gw.alicdn.com/tfscom/TB1q3Nfi6uhSKJjSspmXXcQDpXa.png) +![](https://gw.alicdn.com/tfscom/TB1q3Nfi6uhSKJjSspmXXcQDpXa.png) 使用快捷键(Ctrl+Shift+Alt+J)触发弹出窗口,选择检测范围;您也可自定义快捷键。 - ![](https://gw.alicdn.com/tfscom/TB1k4uXmYwTMeJjSszfXXXbtFXa.png) +![](https://gw.alicdn.com/tfscom/TB1k4uXmYwTMeJjSszfXXXbtFXa.png) - ![](https://gw.alicdn.com/tfscom/TB1ObqXifxNTKJjy0FjXXX6yVXa.png) +![](https://gw.alicdn.com/tfscom/TB1ObqXifxNTKJjy0FjXXX6yVXa.png) #### 扫描结果 -检测结果直接使用IDEA Run Inspection By Name功能的结果界面,插件的检测结果分级为Blocker、Critical、Major。默认按等级分组,方便统计每个级别错误的数量。 +检测结果直接使用IDEA Run Inspection By Name功能的结果界面,插件的检测结果分级为Blocker、Critical、Major、Warning、Weak Warning。默认按等级分组,方便统计每个级别错误的数量。 ![](https://gw.alicdn.com/tfscom/TB1aC1yifJNTKJjSspoXXc6mpXa.png) - +其中,Blocker、Critical、Major三个级别保持与阿里巴巴官方版相同,不会轻易改变。如果未来需要改变,则必须在此Readme中注明。 + +看见有人做了比较有道理的第三方规则的话,会是视情况加入Warning或者Weak Warning。 + +如无例外,一个第三方规则如果在任何情况下都能够执行,即程序员完全可以实现不违背该规则实现任何功能,则这个规则会被放入Warning。 + +与之相对的,如果存在特定的条件,使得若需要满足特定条件则必须违背该规则,即程序员存在必须违背该规则的场景,则这个规则会被放入Weak Warning。 + +如果要使用pmd maven plugin对代码进行自动检查以确保不违反阿里巴巴Java开发手册, + +则请设置`3`,以保证与官方版本规则吻合。 + +使用例可见`p3c-pmd/pom.xml` + 默认情况我们在结果面板需要双击具体违规项才能打开对应的源文件,开启Autoscroll To Source选项,单击面板中的文件名、或者是具体的违规项的时候IDEA会自动打开对应的源文件。 - ![](https://gw.alicdn.com/tfscom/TB1aIixmYsTMeJjy1zcXXXAgXXa.png) +![](https://gw.alicdn.com/tfscom/TB1aIixmYsTMeJjy1zcXXXAgXXa.png) #### QuickFix 对于实现Quick Fix的规则,在结果面板中可以直接一键修复 `注意:IDEA14、15可以通过左下角的灯泡进行一键修复操作。` - ![](https://gw.alicdn.com/tfscom/TB1Kw5Vm3oQMeJjy0FpXXcTxpXa.png) +![](https://gw.alicdn.com/tfscom/TB1Kw5Vm3oQMeJjy0FpXXcTxpXa.png) - ![](https://gw.alicdn.com/tfscom/TB1lHZZiGagSKJjy0FbXXa.mVXa.png) +![](https://gw.alicdn.com/tfscom/TB1lHZZiGagSKJjy0FbXXa.mVXa.png) #### 其他 面板中其他按钮的功能大家自行探索吧,就不一一赘述了 ### 代码提交时检测 1. 在提交代码框勾选Alibaba Code Guidelines选项 - ![](https://gw.alicdn.com/tfscom/TB1u_ZZjamgSKJjSspiXXXyJFXa.png) +![](https://gw.alicdn.com/tfscom/TB1u_ZZjamgSKJjSspiXXXyJFXa.png) 2. 如果有违反手册的地方会提示是否继续提交,选择取消后会自动对修改的代码进行扫描 - ![](https://gw.alicdn.com/tfscom/TB1r5PUXbb85uJjSZFmXXcgsFXa.png) +![](https://gw.alicdn.com/tfscom/TB1r5PUXbb85uJjSZFmXXcgsFXa.png) + +## 设置文件机制 +### 文件目录 +对于p3c idea插件来说,配置文件存放的位置为项目根目录下的p3c_config.x8l文件。 + +对于maven项目来说,配置文件存放的位置为运行mvn的目录下的p3c_config.x8l文件。 + +经常的,这两个位置指向同一个位置。 + +### 文件格式 +文件格式为 [x8l](https://github.com/cyanpotion/x8l). + +### 文件描述 + +举个例子,以 [cyan_potion](https://github.com/cyanpotion/cyan_potionp3c_config.x8l) 为例, +我们来看如何配置p3c_config.x8l + +首先,p3c_config.x8l位于项目根目录。 + +``` + + + + + DAOImpl& + GLFW& + URL& + URI& + XInput& + PosX& + PosY& + AWT& + XY& + drawBoxTC& + FPS& + ID& + lastX& + lastY& + > + > + + + Hbase& + HBase& + ID& + ConcurrentHashMap& + GLFW& + URL& + URI& + JXInput& + SettingFileParser_ + > + > + > + + PackageNamingRule& + AbstractClassShouldStartWithAbstractNamingRule& + ThreadPoolCreationRule& + MethodTooLongRule& + > + + Console + > + + com.xenoamess.cyan_potion.base.steam + > + + EnumConstantsMustHaveCommentRule> + EnumConstantsMustHaveCommentRule> + EnumConstantsMustHaveCommentRule> + EnumConstantsMustHaveCommentRule> + EnumConstantsMustHaveCommentRule> + EnumConstantsMustHaveCommentRule> + + UndefineMagicConstantRule> + + AvoidUseDeprecationRule> + + AvoidUseDeprecationRule> + AvoidUseDeprecationRule> + AvoidUseDeprecationRule> + + LowerCamelCaseVariableNamingRule&AvoidUseDeprecationRule> + + ConstantFieldShouldBeUpperCaseRule> + > +> +``` + +其中,根节点名必为com.alibaba.p3c.pmd.config 。 + +属性version=0.0.1为配置文件version,目前尚未实际应用,但是建议写明,以防后续破坏性更新。 + +对于这个项目,方便/美观起见,我们开启了trim,所有读取的String会被trim,然后再进行处理。 + +例如, + +``` + + Console + > +``` + +中的TextNode + +``` + + Console + +``` + +会被trim为`Console`然后使用。 + +com.alibaba.p3c.pmd.config节点下有四个子节点,以下依次讲解。 + +### rule_config + +rule_config节点主要包括对于提供了设置属性的规则的具体设置。 + +如,LowerCamelCaseVariableNamingRule的WHITE_LIST属性。 + +该属性要求提供一字符串List,则本项目中读取一个ContentNode下多个TextNode转换为字符串List。 + +### rule_blacklist + +rule_blacklist节点主要包括对该项目的所有类禁用某一规则。 + +如,rule_blacklist中含有PackageNamingRule,则表明该项目中,检测器不会检测PackageNamingRule。 + +rule_blacklist中的Rule类名既可以是SimpleName,也可以是CanonicalName。 + +### class_blacklist + +class_blacklist节点主要包括对该项目中的某一类禁用所有规则。 + +如,class_blacklist中含有Console类,则该项目中所有名为Console的类均不会进行任何检测。 + +注意,由于PMD技术原因,class_blacklist中的类必须为SimpleName + +### package_blacklist + +package_blacklist节点主要包括对该项目中的某一个父包禁用所有规则。 + +如,package_blacklist中含有`com.xenoamess`包,则该项目中所有`com.xenoamess`包下的类均不会进行任何检测。 + +注意,形如`com.xenoamess.cyan_potion`的,`com.xenoamess`包的子包也会被禁用所有规则。 + +### rule_class_pair_blacklist + +rule_class_pair_blacklist节点主要包括对该项目中的某一类禁用某数个规则。 + +如,rule_class_pair_blacklist中含有 + +`LowerCamelCaseVariableNamingRule&AvoidUseDeprecationRule>` + +, +则该项目中所有名为GameInputManager的类中,LowerCamelCaseVariableNamingRule与AvoidUseDeprecationRule不会被检测。 + +Rule类名既可以是SimpleName,也可以是CanonicalName。 +注意,由于PMD技术原因,被忽略检测的类名必须为SimpleName。 + +### 为了反X8L主义者干杯 + +如果你确实讨厌X8L文件格式,你可以使用等价json格式配置文件。 + +```json +{ + "com.alibaba.p3c.pmd.config": { + "_attributes": { + "version": "0.0.1" + }, + "rule_config": { + "LowerCamelCaseVariableNamingRule": { + "WHITE_LIST": [ + "DAOImpl", + "GLFW", + "URL", + "URI", + "XInput", + "PosX", + "PosY", + "AWT", + "XY", + "drawBoxTC", + "FPS", + "ID", + "lastX", + "lastY" + ] + }, + "ClassNamingShouldBeCamelRule": { + "CLASS_NAMING_WHITE_LIST": [ + "Hbase", + "HBase", + "ID", + "ConcurrentHashMap", + "GLFW", + "URL", + "URI", + "JXInput", + "SettingFileParser_" + ] + } + }, + "rule_blacklist": [ + "PackageNamingRule", + "AbstractClassShouldStartWithAbstractNamingRule", + "ThreadPoolCreationRule", + "MethodTooLongRule" + ], + "class_blacklist": [ + "Console" + ], + "package_blacklist": [ + "com.xenoamess.cyan_potion.base.steam" + ], + "rule_class_pair_blacklist": { + "JamepadGamepadKeyEnum": [ + "EnumConstantsMustHaveCommentRule" + ], + "JXInputGamepadKeyEnum": [ + "EnumConstantsMustHaveCommentRule" + ], + "KeyActionEnum": [ + "EnumConstantsMustHaveCommentRule" + ], + "KeyboardKeyEnum": [ + "EnumConstantsMustHaveCommentRule" + ], + "CodePluginPosition": [ + "EnumConstantsMustHaveCommentRule" + ], + "ShapeRelation": [ + "EnumConstantsMustHaveCommentRule" + ], + "WaveData": [ + "UndefineMagicConstantRule" + ], + "FileUtils": [ + "AvoidUseDeprecationRule" + ], + "Font": [ + "AvoidUseDeprecationRule" + ], + "Keymap": [ + "AvoidUseDeprecationRule" + ], + "WorldForDemo": [ + "AvoidUseDeprecationRule" + ], + "GameInputManager": [ + "LowerCamelCaseVariableNamingRule", + "AvoidUseDeprecationRule" + ], + "Colors": [ + "ConstantFieldShouldBeUpperCaseRule" + ] + } + } +} +``` + +文件名为p3c_config.json即可。 diff --git a/idea-plugin/build.gradle b/idea-plugin/build.gradle index 64aa3dbb7..48b43b88b 100644 --- a/idea-plugin/build.gradle +++ b/idea-plugin/build.gradle @@ -1,38 +1,64 @@ +static boolean shouldIncludeJava(String idea_version_string) { + if (idea_version_string.contains('-')) { + idea_version_string = idea_version_string.substring(idea_version_string.indexOf('-') + 1) + } + if (idea_version_string.contains('.')) { + idea_version_string = idea_version_string.substring(0, idea_version_string.indexOf('.')) + } + try { + int idea_version_int = Integer.parseInt(idea_version_string); + return idea_version_int >= 2019 || (idea_version_int < 1500 && idea_version_int >= 193); + } catch (Exception e) { + return true + } +} + buildscript { + project.ext { + kotlin_version = "2.2.21" + } repositories { + mavenCentral() + mavenLocal() maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } maven { - url 'http://dl.bintray.com/jetbrains/intellij-plugin-service' + url "https://plugins.gradle.org/m2/" } - mavenCentral() - + gradlePluginPortal() + google() } dependencies { - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$project.kotlin_version" } } allprojects { - group 'com.alibaba.p3c.idea' + group 'com.xenoamess.p3c.idea' apply plugin: 'java' apply plugin: 'kotlin' apply plugin: 'maven-publish' - - sourceCompatibility = 1.8 + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 compileJava.options.encoding = 'UTF-8' + kotlin { + jvmToolchain(17) + } configurations.all { resolutionStrategy.cacheChangingModulesFor 0, 'seconds' } repositories { - jcenter() mavenCentral() - } - - dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - testCompile group: 'junit', name: 'junit', version: '4.11' + mavenLocal() + maven { + url "https://oss.sonatype.org/content/repositories/snapshots/" + } + maven { + url "https://plugins.gradle.org/m2/" + } + gradlePluginPortal() + google() } } diff --git a/idea-plugin/gradle.properties b/idea-plugin/gradle.properties index 637c314fa..b65de0735 100644 --- a/idea-plugin/gradle.properties +++ b/idea-plugin/gradle.properties @@ -1,7 +1,12 @@ -kotlin_version=1.3.72 -idea_version=2018.3 +# See https://github.com/JetBrains/gradle-intellij-plugin/ +# See https://www.jetbrains.org/intellij/sdk/docs/reference_guide/intellij_artifacts.html +# See https://www.jetbrains.com/intellij-repository/releases/ +# See https://www.jetbrains.com/intellij-repository/snapshots/ +#idea_version=2022.1 +idea_version=2024.1 +#idea_version=181.5540.23 +#idea_version=145.258.11 plugin_name=Alibaba Java Coding Guidelines -gradle_jetbrains_version=0.4.5 systemProp.file.encoding=UTF-8 - -plugin_version=2.1.0 +plugin_version=2.2.4.0x-SNAPSHOT +org.gradle.jvmargs='-Dfile.encoding=UTF-8' diff --git a/idea-plugin/gradle/wrapper/gradle-wrapper.jar b/idea-plugin/gradle/wrapper/gradle-wrapper.jar index 62d4c0535..f3d88b1c2 100644 Binary files a/idea-plugin/gradle/wrapper/gradle-wrapper.jar and b/idea-plugin/gradle/wrapper/gradle-wrapper.jar differ diff --git a/idea-plugin/gradle/wrapper/gradle-wrapper.properties b/idea-plugin/gradle/wrapper/gradle-wrapper.properties index 6c9a22477..067e85613 100644 --- a/idea-plugin/gradle/wrapper/gradle-wrapper.properties +++ b/idea-plugin/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,6 @@ +#Sat Sep 21 06:16:57 CST 2024 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.6-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.1-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/idea-plugin/gradlew b/idea-plugin/gradlew old mode 100755 new mode 100644 diff --git a/idea-plugin/p3c-common/build.gradle b/idea-plugin/p3c-common/build.gradle index 69ff629e6..31bd4a597 100644 --- a/idea-plugin/p3c-common/build.gradle +++ b/idea-plugin/p3c-common/build.gradle @@ -1,9 +1,14 @@ plugins { - id "org.jetbrains.intellij" version '0.4.5' + id 'java' + id "org.jetbrains.intellij" version "1.17.4" + + id "org.sonarqube" version "6.3.1.5724" + + id "com.github.ben-manes.versions" version "0.53.0" } + apply plugin: 'kotlin' apply plugin: 'idea' -apply plugin: 'maven' apply plugin: 'signing' javadoc { @@ -11,12 +16,14 @@ javadoc { } task javadocJar(type: Jar, dependsOn: javadoc) { - classifier = 'javadoc' + archiveClassifier.convention('javadoc'); + archiveClassifier.set('javadoc'); from 'build/docs/javadoc' } task sourcesJar(type: Jar) { - classifier = 'sources' + archiveClassifier.convention('sources'); + archiveClassifier.set('sources'); from sourceSets.main.allSource } @@ -27,76 +34,40 @@ artifacts { } def myPlugins = [] -def versionDotIndex = idea_version.indexOf('.') -def intVersion = versionDotIndex == -1 ? Integer.parseInt(idea_version) : Integer.parseInt(idea_version.substring(0, versionDotIndex)) -if (intVersion >= 2019 || (intVersion < 1000 && intVersion >= 193)) { - myPlugins = ['java'] +if (shouldIncludeJava(idea_version)) { + myPlugins.add('java') +} + +sonarqube { + properties { + property "sonar.projectKey", "p3c-idea" + property "sonar.organization", "xenoamess-github" + property "sonar.host.url", "https://sonarcloud.io" + property "sonar.login", "023904832cfec46a1aa61bb7aeee156b066cb3bc" + } } intellij { - version idea_version - plugins = myPlugins - pluginName plugin_name - updateSinceUntilBuild false - sandboxDirectory "$project.buildDir/idea-sandbox/$idea_version" + version.set(idea_version) + plugins.set(myPlugins) + pluginName.set(plugin_name) + updateSinceUntilBuild.set(false) + sandboxDir.set("$project.buildDir/idea-sandbox/$idea_version") } -version '2.0.1' +version plugin_version ext.isReleaseVersion = !version.endsWith("SNAPSHOT") dependencies { - compile group: 'org.freemarker', name: 'freemarker', version: '2.3.25-incubating' - compile 'com.alibaba.p3c:p3c-pmd:2.1.0' - compile group: 'org.javassist', name: 'javassist', version: '3.21.0-GA' -} - -uploadArchives { - repositories { - mavenDeployer { - beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } - - repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") { - authentication(userName: findProperty('ossrhUsername'), password: findProperty('ossrhPassword')) - } - - snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") { - authentication(userName: findProperty('ossrhUsername'), password: findProperty('ossrhPassword')) - } - - pom.project { - name 'p3c-common' - packaging 'jar' - description 'P3c Idea Plugin Common.' - url 'https://github.com/alibaba/p3c' - - scm { - url 'https://github.com/alibaba/p3c' - connection 'scm:git:https://git@github.com/alibaba/p3c.git' - } - - licenses { - license { - name 'The Apache Software License, Version 2.0' - url 'http://www.apache.org/licenses/LICENSE-2.0.txt' - distribution 'repo' - } - } - - developers { - developer { - id 'junlie' - name 'Junlie' - email 'sean.caikang@gmail.com' - } - developer { - id 'ZengHou' - name 'ZengHou' - email 'fengwei1983@gmail.com' - } - } - } - } + implementation group: 'org.freemarker', name: 'freemarker', version: '2.3.33' + implementation("com.xenoamess.p3c:p3c-pmd:$plugin_version") { + exclude group: 'org.apache.logging.log4j' + exclude group: 'org.slf4j' } + implementation group: 'org.javassist', name: 'javassist', version: '3.30.2-GA' + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$project.kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-reflect:$project.kotlin_version" + testImplementation group: 'junit', name: 'junit', version: '4.13.2' } signing { diff --git a/idea-plugin/p3c-common/src/main/java/icons/P3cIcons.java b/idea-plugin/p3c-common/src/main/java/icons/P3cIcons.java index a4908c677..03b94b498 100644 --- a/idea-plugin/p3c-common/src/main/java/icons/P3cIcons.java +++ b/idea-plugin/p3c-common/src/main/java/icons/P3cIcons.java @@ -26,13 +26,20 @@ public final class P3cIcons { private P3cIcons() { throw new AssertionError("icons.P3cIcons" - + " instances for you!"); + + " instances for you!"); } - public static final Icon ANALYSIS_ACTION = IconLoader.getIcon("/icons/ali-ide-run.png"); + public static final Icon ANALYSIS_ACTION = IconLoader.getIcon("/icons/ali-ide-run.png", P3cIcons.class); - public static final Icon PROJECT_INSPECTION_ON = IconLoader.getIcon("/icons/qiyong.png"); - public static final Icon PROJECT_INSPECTION_OFF = IconLoader.getIcon("/icons/tingyong.png"); - public static final Icon LANGUAGE = IconLoader.getIcon("/icons/language.png"); - public static final Icon ALIBABA = IconLoader.getIcon("/icons/alibaba.png"); + /** + * qiyong means 启用 + */ + public static final Icon PROJECT_INSPECTION_ON = IconLoader.getIcon("/icons/qiyong.png", P3cIcons.class); + + /** + * tingyong means 停用 + */ + public static final Icon PROJECT_INSPECTION_OFF = IconLoader.getIcon("/icons/tingyong.png", P3cIcons.class); + public static final Icon LANGUAGE = IconLoader.getIcon("/icons/language.png", P3cIcons.class); + public static final Icon ALIBABA = IconLoader.getIcon("/icons/alibaba.png", P3cIcons.class); } 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 a43af5b8a..d1a884eb9 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 @@ -24,23 +24,19 @@ import com.google.common.collect.Lists import com.intellij.analysis.AnalysisScope import com.intellij.analysis.AnalysisUIOptions import com.intellij.analysis.BaseAnalysisActionDialog +import com.intellij.analysis.problemsView.toolWindow.ProblemsView import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.InspectionsBundle import com.intellij.codeInspection.ex.GlobalInspectionContextImpl import com.intellij.codeInspection.ex.InspectionManagerEx import com.intellij.codeInspection.ex.InspectionToolWrapper -import com.intellij.openapi.actionSystem.AnAction -import com.intellij.openapi.actionSystem.AnActionEvent -import com.intellij.openapi.actionSystem.CommonDataKeys -import com.intellij.openapi.components.ServiceManager +import com.intellij.openapi.actionSystem.* import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile -import com.intellij.openapi.wm.ToolWindowId -import com.intellij.openapi.wm.ToolWindowManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiFileSystemItem @@ -55,7 +51,7 @@ class AliInspectionAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return - val analysisUIOptions = ServiceManager.getService(project, AnalysisUIOptions::class.java)!! + val analysisUIOptions = project.getService(AnalysisUIOptions::class.java)!! analysisUIOptions.GROUP_BY_SEVERITY = true val managerEx = InspectionManager.getInstance(project) as InspectionManagerEx @@ -114,9 +110,13 @@ class AliInspectionAction : AnAction() { } private fun inspectForKeyEvent( - project: Project, managerEx: InspectionManagerEx, - toolWrappers: List>, psiElement: PsiElement?, psiFile: PsiFile?, - virtualFile: VirtualFile?, analysisScope: AnalysisScope + project: Project, + managerEx: InspectionManagerEx, + toolWrappers: List>, + psiElement: PsiElement?, + psiFile: PsiFile?, + virtualFile: VirtualFile?, + analysisScope: AnalysisScope ) { var module: Module? = null if (virtualFile != null && project.baseDir != virtualFile) { @@ -126,14 +126,23 @@ class AliInspectionAction : AnAction() { val uiOptions = AnalysisUIOptions.getInstance(project) uiOptions.ANALYZE_TEST_SOURCES = false val dialog = BaseAnalysisActionDialog( - "Select Analyze Scope", "Analyze Scope", project, analysisScope, - module?.name, true, uiOptions, psiElement + "Select Analyze Scope", + "Analyze Scope", + project, + BaseAnalysisActionDialog.standardItems( + project, + analysisScope, + module, + psiElement + ), + uiOptions, + true ) if (!dialog.showAndGet()) { return } - val scope = dialog.getScope(uiOptions, analysisScope, project, module) + val scope = dialog.getScope(analysisScope) scope.setSearchInLibraries(true) val element = psiFile ?: psiElement createContext( @@ -163,11 +172,11 @@ class AliInspectionAction : AnAction() { } fun createContext( - toolWrapperList: List>, - managerEx: InspectionManagerEx, psiElement: PsiElement?, - projectScopeSelected: Boolean, scope: AnalysisScope + toolWrapperList: List>, + managerEx: InspectionManagerEx, psiElement: PsiElement?, + projectScopeSelected: Boolean, scope: AnalysisScope ): - GlobalInspectionContextImpl { + GlobalInspectionContextImpl { // remove last same scope content val project = managerEx.project val title = getTitle(psiElement, projectScopeSelected) @@ -177,12 +186,11 @@ class AliInspectionAction : AnAction() { } val inspectionContext = createNewGlobalContext( - managerEx, projectScopeSelected + managerEx, projectScopeSelected ) InspectionProfileService.setExternalProfile(model, inspectionContext) - val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.INSPECTION) - + val toolWindow = ProblemsView.getToolWindow(project); if (toolWindow != null) { val contentManager = toolWindow.contentManager val contentTitle = title?.let { @@ -206,4 +214,9 @@ class AliInspectionAction : AnAction() { return PmdGlobalInspectionContextImpl(managerEx.project, managerEx.contentManager, projectScopeSelected) } } + + override fun getActionUpdateThread(): ActionUpdateThread { + return ActionUpdateThread.BGT + } + } diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/PmdGlobalInspectionContextImpl.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/PmdGlobalInspectionContextImpl.kt index f7c277872..69bd1bc14 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/PmdGlobalInspectionContextImpl.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/PmdGlobalInspectionContextImpl.kt @@ -116,7 +116,7 @@ class PmdGlobalInspectionContextImpl( logger.info(file.name + "; scope: " + scope + "; " + virtualFile) return@tryRunReadActionInSmartMode true } - val path = virtualFile.canonicalPath?.toLowerCase() ?: "" + val path = virtualFile.canonicalPath?.lowercase() ?: "" if (!path.endsWith(".java") && !path.endsWith(".vm")) { return@tryRunReadActionInSmartMode true } @@ -227,43 +227,50 @@ class PmdGlobalInspectionContextImpl( ): Future<*>? { val task: Backgroundable = object : Backgroundable(project, "Scanning Files to Inspect") { override fun run(indicator: ProgressIndicator) { - try { - val fileIndex: FileIndex = ProjectRootManager.getInstance(project).fileIndex - scope.accept { file: VirtualFile? -> - ProgressManager.checkCanceled() - if (isProjectOrWorkspaceFile(file!!) || !fileIndex.isInContent(file)) return@accept true - val psiFile = - ReadAction.compute { - if (project.isDisposed) throw ProcessCanceledException() - val psi = PsiManager.getInstance(project).findFile(file) - val document = - psi?.let { shouldProcess(it, headlessEnvironment, localScopeFiles) } - if (document != null) { - return@compute psi + ApplicationManager.getApplication().runReadAction( + Runnable { + try { + val fileIndex: FileIndex = ProjectRootManager.getInstance(project).fileIndex + scope.accept { file: VirtualFile? -> + ProgressManager.checkCanceled() + if (isProjectOrWorkspaceFile(file!!) || !fileIndex.isInContent(file)) return@accept true + val psiFile = + ReadAction.compute { + if (project.isDisposed) throw ProcessCanceledException() + val psi = PsiManager.getInstance(project).findFile(file) + val document = + psi?.let { shouldProcess(it, headlessEnvironment, localScopeFiles) } + if (document != null) { + return@compute psi + } + null + } + // do not inspect binary files + if (psiFile != null) { + try { + if (ApplicationManager.getApplication().isReadAccessAllowed) { + outFilesToInspect.put(psiFile) + } + } catch (e: InterruptedException) { + logger.error("psiFile interrupted : " + psiFile.name, e) + } catch (e: IllegalStateException) { + logger.info("psiFile ignored : " + psiFile.name, e) + } } - null + ProgressManager.checkCanceled() + true } - // do not inspect binary files - if (psiFile != null) { + } catch (e: ProcessCanceledException) { + // ignore, but put tombstone + } finally { try { - check(!ApplicationManager.getApplication().isReadAccessAllowed) { "Must not have read action" } - outFilesToInspect.put(psiFile) + outFilesToInspect.put(PsiUtilCore.NULL_PSI_FILE) } catch (e: InterruptedException) { logger.error(e) } } - ProgressManager.checkCanceled() - true } - } catch (e: ProcessCanceledException) { - // ignore, but put tombstone - } finally { - try { - outFilesToInspect.put(PsiUtilCore.NULL_PSI_FILE) - } catch (e: InterruptedException) { - logger.error(e) - } - } + ) } } return (ProgressManager.getInstance() as CoreProgressManager).runProcessWithProgressAsynchronously( diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/SwitchLanguageAction.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/SwitchLanguageAction.kt index df7d39f00..f4a75344a 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/SwitchLanguageAction.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/SwitchLanguageAction.kt @@ -20,6 +20,7 @@ import com.alibaba.p3c.idea.i18n.P3cBundle import com.alibaba.smartfox.idea.common.util.BalloonNotifications import com.alibaba.smartfox.idea.common.util.getService import com.intellij.notification.NotificationListener +import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ex.ApplicationManagerEx @@ -48,4 +49,9 @@ class SwitchLanguageAction : AnAction(), DumbAware { override fun update(e: AnActionEvent) { e.presentation.text = P3cBundle.getMessage("$textKey.cur_${p3cConfig.locale}") } + + override fun getActionUpdateThread(): ActionUpdateThread { + return ActionUpdateThread.EDT + } + } 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 a7ffd0b62..8d9287c10 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 @@ -20,6 +20,7 @@ import com.alibaba.p3c.idea.compatible.inspection.Inspections import com.alibaba.p3c.idea.config.SmartFoxProjectConfig import com.alibaba.p3c.idea.i18n.P3cBundle import com.alibaba.p3c.idea.inspection.AliBaseInspection +import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.components.ServiceManager @@ -37,7 +38,7 @@ class ToggleProjectInspectionAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return - val smartFoxConfig = ServiceManager.getService(project, SmartFoxProjectConfig::class.java) + val smartFoxConfig = project.getService(SmartFoxProjectConfig::class.java) val tools = Inspections.aliInspections(project) { it.tool is AliBaseInspection } @@ -47,7 +48,7 @@ class ToggleProjectInspectionAction : AnAction() { override fun update(e: AnActionEvent) { val project = e.project ?: return - val smartFoxConfig = ServiceManager.getService(project, SmartFoxProjectConfig::class.java) + val smartFoxConfig = project.getService(SmartFoxProjectConfig::class.java) e.presentation.text = if (smartFoxConfig.projectInspectionClosed) { e.presentation.icon = P3cIcons.PROJECT_INSPECTION_ON P3cBundle.getMessage("$textKey.open") @@ -56,4 +57,9 @@ class ToggleProjectInspectionAction : AnAction() { P3cBundle.getMessage("$textKey.close") } } + + override fun getActionUpdateThread(): ActionUpdateThread { + return ActionUpdateThread.BGT + } + } diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/activity/CommonSettingsApplicationStartupActivity.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/activity/CommonSettingsApplicationStartupActivity.kt new file mode 100644 index 000000000..abd5af5b7 --- /dev/null +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/activity/CommonSettingsApplicationStartupActivity.kt @@ -0,0 +1,54 @@ +/* + * 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.activity + +import com.alibaba.p3c.idea.config.P3cConfig +import com.alibaba.p3c.idea.i18n.P3cBundle +import com.alibaba.p3c.idea.util.HighlightInfoTypes +import com.alibaba.p3c.idea.util.HighlightSeverities +import com.xenoamess.p3c.pmd.I18nResources +import com.alibaba.smartfox.idea.common.activity.AliBaseApplicationStartupActivity +import com.intellij.codeInsight.daemon.impl.SeverityRegistrar +import com.intellij.openapi.actionSystem.ActionManager +import com.intellij.openapi.project.Project + +/** + * + * + * @author caikang + * @date 2017/06/19 + */ +class CommonSettingsApplicationStartupActivity : AliBaseApplicationStartupActivity { + companion object { + const val analyticsGroupId = "com.alibaba.p3c.analytics.action_group" + val analyticsGroupText = "$analyticsGroupId.text" + private val p3cConfig = P3cConfig() + } + + override fun runActivity(project: Project) { + SeverityRegistrar.registerStandard(HighlightInfoTypes.BLOCKER, HighlightSeverities.BLOCKER) + SeverityRegistrar.registerStandard(HighlightInfoTypes.CRITICAL, HighlightSeverities.CRITICAL) + SeverityRegistrar.registerStandard(HighlightInfoTypes.MAJOR, HighlightSeverities.MAJOR) + +// Shall not register WARNING and WEAK_WARNING! +// SeverityRegistrar.registerStandard(HighlightInfoTypes.WARNING, HighlightSeverities.WARNING) +// SeverityRegistrar.registerStandard(HighlightInfoTypes.WEAK_WARNING, HighlightSeverities.WEAK_WARNING) + + I18nResources.changeLanguage(p3cConfig.locale) + val analyticsGroup = ActionManager.getInstance().getAction(analyticsGroupId) + analyticsGroup.templatePresentation.text = P3cBundle.getMessage(analyticsGroupText) + } +} diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/compatible/inspection/InspectionProfileService.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/compatible/inspection/InspectionProfileService.kt index eff136427..8dd8f7622 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/compatible/inspection/InspectionProfileService.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/compatible/inspection/InspectionProfileService.kt @@ -36,8 +36,11 @@ import java.util.LinkedHashSet * @date 2017/03/01 */ object InspectionProfileService { - fun createSimpleProfile(toolWrapperList: List>, - managerEx: InspectionManagerEx, psiElement: PsiElement?): InspectionProfileImpl { + fun createSimpleProfile( + toolWrapperList: List>, + managerEx: InspectionManagerEx, + psiElement: PsiElement? + ): InspectionProfileImpl { val profile = getProjectInspectionProfile(managerEx.project) val allWrappers: LinkedHashSet> = Sets.newLinkedHashSet() allWrappers.addAll(toolWrapperList) @@ -84,7 +87,11 @@ object InspectionProfileService { return model } - fun toggleInspection(project: Project, aliInspections: List>, closed: Boolean) { + fun toggleInspection( + project: Project, + aliInspections: List>, + closed: Boolean + ) { val profile = getProjectInspectionProfile(project) val shortNames = aliInspections.map { it.tool.shortName @@ -102,8 +109,10 @@ object InspectionProfileService { profile.scopesChanged() } - fun setExternalProfile(profile: InspectionProfileImpl, - inspectionContext: GlobalInspectionContextImpl) { + fun setExternalProfile( + profile: InspectionProfileImpl, + inspectionContext: GlobalInspectionContextImpl + ) { val method = inspectionContext.javaClass.methods.first { it.name == "setExternalProfile" && it.parameterTypes.size == 1 && it.parameterTypes.first().isAssignableFrom(InspectionProfileImpl::class.java) } @@ -111,6 +120,6 @@ object InspectionProfileService { } fun getProjectInspectionProfile(project: Project): InspectionProfileImpl { - return InspectionProjectProfileManager.getInstance(project).inspectionProfile as InspectionProfileImpl + return InspectionProjectProfileManager.getInstance(project).currentProfile } } diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/compatible/inspection/Inspections.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/compatible/inspection/Inspections.kt index 1c186c495..fad308363 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/compatible/inspection/Inspections.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/compatible/inspection/Inspections.kt @@ -15,12 +15,29 @@ */ package com.alibaba.p3c.idea.compatible.inspection +import com.xenoamess.p3c.pmd.lang.java.util.namelist.NameListConfig import com.google.common.base.Splitter import com.intellij.codeInspection.ex.InspectionProfileImpl import com.intellij.codeInspection.ex.InspectionToolWrapper import com.intellij.codeInspection.ex.ScopeToolState -import com.intellij.codeInspection.javaDoc.JavaDocLocalInspection import com.intellij.openapi.project.Project +import com.intellij.openapi.util.JDOMExternalizerUtil +import com.xenoamess.p3c.pmd.lang.java.util.namelist.NameListServiceImpl.P3C_JSON_CONFIG_FILE_NAME +import com.xenoamess.p3c.pmd.lang.java.util.namelist.NameListServiceImpl.P3C_X8L_CONFIG_FILE_NAME +import org.apache.commons.lang3.StringUtils +import org.jdom.Element +import org.jetbrains.annotations.SystemIndependent +import java.io.File +import java.io.FilenameFilter + +/** + * @author XenoAmess + */ +class P3cConfigFilenameFilter : FilenameFilter { + override fun accept(dir: File?, name: String?): Boolean { + return P3C_X8L_CONFIG_FILE_NAME.equals(name) || P3C_JSON_CONFIG_FILE_NAME.equals(name) + } +} /** * @@ -30,26 +47,52 @@ import com.intellij.openapi.project.Project */ object Inspections { fun aliInspections(project: Project, filter: (InspectionToolWrapper<*, *>) -> Boolean): List> { + loadPatchConfigFile(project) val profile = InspectionProfileService.getProjectInspectionProfile(project) return getAllTools(project, profile).filter(filter) } - fun addCustomTag(project: Project, tag: String) { - val profile = InspectionProfileService.getProjectInspectionProfile(project) - val javaDocLocalInspection = profile.getInspectionTool("JavaDoc", project)?.tool - as? JavaDocLocalInspection ?: return - if (javaDocLocalInspection.myAdditionalJavadocTags.isEmpty()) { - javaDocLocalInspection.myAdditionalJavadocTags = tag - return + fun loadPatchConfigFile(project: Project) { + val patchConfigFile = fetchPatchConfigFile(project) + if (patchConfigFile == null) { + NameListConfig.renewNameListService() + } else { + NameListConfig.renewNameListService(patchConfigFile) } + } + + private fun fetchPatchConfigFile(project: Project): File? { + val projectBasePath: @SystemIndependent String? = project.basePath + ?: return null + val projectBaseFile = File(projectBasePath) + val fileList = projectBaseFile.listFiles(P3cConfigFilenameFilter()) + return if (fileList == null || fileList.isEmpty()) { + null + } else { + fileList[0] + } + } + + + fun addCustomTag(project: Project, tag: String) { + try { + val profile = InspectionProfileService.getProjectInspectionProfile(project) + val javaDocLocalInspection : Element = profile.getInspectionTool("JavaDoc", project)?.tool as? Element ?: return + val myAdditionalJavadocTags : String? = JDOMExternalizerUtil.readField(javaDocLocalInspection, "myAdditionalJavadocTags") + if (StringUtils.isEmpty(myAdditionalJavadocTags)) { + JDOMExternalizerUtil.writeField(javaDocLocalInspection, "myAdditionalJavadocTags", tag) + return + } - val tags = Splitter.on(',').splitToList(javaDocLocalInspection.myAdditionalJavadocTags) - if (tags.contains(tag)) { - return + val tags = Splitter.on(',').splitToList(myAdditionalJavadocTags) + if (tags.contains(tag)) { + return + } + JDOMExternalizerUtil.writeField(javaDocLocalInspection, "myAdditionalJavadocTags", myAdditionalJavadocTags + ",$tag") + profile.profileChanged() + profile.scopesChanged() + } catch (ignored : Exception) { } - javaDocLocalInspection.myAdditionalJavadocTags += "," + tag - profile.profileChanged() - profile.scopesChanged() } private fun getAllTools(project: Project, profile: InspectionProfileImpl): List> { diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/component/AliProjectComponent.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/component/AliProjectComponent.kt index 4884ea5fb..113852341 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/component/AliProjectComponent.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/component/AliProjectComponent.kt @@ -21,17 +21,17 @@ import com.alibaba.p3c.idea.i18n.P3cBundle import com.alibaba.p3c.idea.inspection.AliPmdInspectionInvoker import com.alibaba.p3c.idea.pmd.SourceCodeProcessor import com.alibaba.p3c.idea.util.withLockNotInline -import com.alibaba.p3c.pmd.I18nResources import com.alibaba.smartfox.idea.common.component.AliBaseProjectComponent +import com.alibaba.smartfox.idea.common.util.getService import com.intellij.openapi.actionSystem.ActionManager -import com.intellij.openapi.project.Project +import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.vfs.VirtualFile -import com.intellij.openapi.vfs.VirtualFileAdapter import com.intellij.openapi.vfs.VirtualFileEvent import com.intellij.openapi.vfs.VirtualFileListener import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.VirtualFileMoveEvent import com.intellij.psi.PsiManager +import com.xenoamess.p3c.pmd.I18nResources import net.sourceforge.pmd.RuleViolation import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.locks.ReentrantReadWriteLock @@ -40,10 +40,7 @@ import java.util.concurrent.locks.ReentrantReadWriteLock * @author caikang * @date 2016/12/13 */ -class AliProjectComponent( - private val project: Project, - val p3cConfig: P3cConfig -) : AliBaseProjectComponent { +class AliProjectComponent : AliBaseProjectComponent { private val listener: VirtualFileListener private val javaExtension = ".java" private val velocityExtension = ".vm" @@ -55,10 +52,12 @@ class AliProjectComponent( private val fileContexts = ConcurrentHashMap() init { - listener = object : VirtualFileAdapter() { + listener = object : VirtualFileListener { override fun contentsChanged(event: VirtualFileEvent) { val path = getFilePath(event) ?: return + val project = ProjectManager.getInstance().defaultProject PsiManager.getInstance(project).findFile(event.file) ?: return + val p3cConfig = P3cConfig::class.java.getService() if (!p3cConfig.ruleCacheEnable) { AliPmdInspectionInvoker.refreshFileViolationsCache(event.file) } @@ -98,12 +97,14 @@ class AliProjectComponent( } override fun initComponent() { + val p3cConfig = P3cConfig::class.java.getService() I18nResources.changeLanguage(p3cConfig.locale) val analyticsGroup = ActionManager.getInstance().getAction(analyticsGroupId) analyticsGroup.templatePresentation.text = P3cBundle.getMessage(analyticsGroupText) } override fun projectOpened() { + val project = ProjectManager.getInstance().defaultProject Inspections.addCustomTag(project, "date") VirtualFileManager.getInstance().addVirtualFileListener(listener) } diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/component/CommonSettingsApplicationComponent.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/component/CommonSettingsApplicationComponent.kt deleted file mode 100644 index 7be5613c8..000000000 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/component/CommonSettingsApplicationComponent.kt +++ /dev/null @@ -1,35 +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.component - -import com.alibaba.p3c.idea.util.HighlightInfoTypes -import com.alibaba.p3c.idea.util.HighlightSeverities -import com.alibaba.smartfox.idea.common.component.AliBaseApplicationComponent -import com.intellij.codeInsight.daemon.impl.SeverityRegistrar - -/** - * - * - * @author caikang - * @date 2017/06/19 - */ -class CommonSettingsApplicationComponent : AliBaseApplicationComponent { - override fun initComponent() { - SeverityRegistrar.registerStandard(HighlightInfoTypes.BLOCKER, HighlightSeverities.BLOCKER) - SeverityRegistrar.registerStandard(HighlightInfoTypes.CRITICAL, HighlightSeverities.CRITICAL) - SeverityRegistrar.registerStandard(HighlightInfoTypes.MAJOR, HighlightSeverities.MAJOR) - } -} diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/ep/InspectionActionExtensionPoint.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/ep/InspectionActionExtensionPoint.kt index 0a4c457e7..8309d16f9 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/ep/InspectionActionExtensionPoint.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/ep/InspectionActionExtensionPoint.kt @@ -34,6 +34,6 @@ interface InspectionActionExtensionPoint { companion object { val extension = ExtensionPointName.create( - "${PluginVersions.pluginId.idString}.inspectionAction")!! + "${PluginVersions.pluginId.idString}.inspectionAction") } } \ No newline at end of file diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/i18n/P3cBundle.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/i18n/P3cBundle.kt index cbd83e8d4..9439f71a8 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/i18n/P3cBundle.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/i18n/P3cBundle.kt @@ -16,11 +16,13 @@ package com.alibaba.p3c.idea.i18n import com.alibaba.p3c.idea.config.P3cConfig -import com.alibaba.p3c.pmd.I18nResources +import com.xenoamess.p3c.pmd.I18nResources import com.alibaba.smartfox.idea.common.util.getService -import com.intellij.CommonBundle +import com.intellij.AbstractBundle +import com.intellij.openapi.application.CachedSingletonsRegistry import java.util.Locale import java.util.ResourceBundle +import java.util.function.Supplier /** * @@ -29,15 +31,23 @@ import java.util.ResourceBundle * @date 2017/06/20 */ object P3cBundle { - private val p3cConfig = P3cConfig::class.java.getService() - private val resourceBundle = ResourceBundle.getBundle("messages.P3cBundle", - Locale(p3cConfig.locale), I18nResources.XmlControl()) + private val p3cConfigSupplier: Supplier = + CachedSingletonsRegistry.lazy { + P3cConfig::class.java.getService() + } + private val resourceBundleSupplier = + CachedSingletonsRegistry.lazy { + ResourceBundle.getBundle( + "messages.P3cBundle", + Locale(p3cConfigSupplier.get().locale), I18nResources.XmlControl() + ) + } fun getMessage(key: String): String { - return resourceBundle.getString(key).trim() + return resourceBundleSupplier.get().getString(key).trim() } fun message(key: String, vararg params: Any): String { - return CommonBundle.message(resourceBundle, key, *params).trim() + return AbstractBundle.message(resourceBundleSupplier.get(), key, *params).trim() } } diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliAccessToNonThreadSafeStaticFieldFromInstanceInspection.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliAccessToNonThreadSafeStaticFieldFromInstanceInspection.kt index 9f01b7e3a..339c87473 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliAccessToNonThreadSafeStaticFieldFromInstanceInspection.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliAccessToNonThreadSafeStaticFieldFromInstanceInspection.kt @@ -27,6 +27,7 @@ class AliAccessToNonThreadSafeStaticFieldFromInstanceInspection : AccessToNonThreadSafeStaticFieldFromInstanceInspection, AliBaseInspection { constructor() + /** * For Javassist */ diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliArrayNamingShouldHaveBracketInspection.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliArrayNamingShouldHaveBracketInspection.kt index 3fbd2e4a4..5ad9b81da 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliArrayNamingShouldHaveBracketInspection.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliArrayNamingShouldHaveBracketInspection.kt @@ -35,6 +35,7 @@ import javax.swing.JComponent */ class AliArrayNamingShouldHaveBracketInspection : CStyleArrayDeclarationInspection, AliBaseInspection { constructor() + /** * ForJavassist */ diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliBaseInspection.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliBaseInspection.kt index a674ee347..fc0e71c8a 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliBaseInspection.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliBaseInspection.kt @@ -65,18 +65,22 @@ interface AliBaseInspection { /** * inspection short name - * @return shor name + * @return short name */ fun getShortName(): String fun manualBuildFix(psiElement: PsiElement, isOnTheFly: Boolean): LocalQuickFix? = null - fun manualParsePsiElement(psiFile: PsiFile, manager: InspectionManager, - start: Int, end: Int): PsiElement { + fun manualParsePsiElement( + psiFile: PsiFile, + manager: InspectionManager, + start: Int, + end: Int + ): PsiElement { return psiFile.findElementAt(start)!! } companion object { - val GROUP_NAME = "Ali-Check" + const val GROUP_NAME = "Ali-Check" } } diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliControlFlowStatementWithoutBracesInspection.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliControlFlowStatementWithoutBracesInspection.kt index 8a5d7ec7f..830d84f7e 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliControlFlowStatementWithoutBracesInspection.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliControlFlowStatementWithoutBracesInspection.kt @@ -32,6 +32,7 @@ class AliControlFlowStatementWithoutBracesInspection : ControlFlowStatementWithoutBracesInspection, AliBaseInspection { constructor() + /** * For Javassist */ diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliEqualsAvoidNullInspection.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliEqualsAvoidNullInspection.kt index 2e7e5f55d..aa4569c6a 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliEqualsAvoidNullInspection.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliEqualsAvoidNullInspection.kt @@ -42,6 +42,7 @@ import org.jetbrains.annotations.NonNls */ class AliEqualsAvoidNullInspection : LiteralAsArgToStringEqualsInspection, AliBaseInspection { constructor() + /** * For Javassist */ diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliLocalInspectionToolProvider.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliLocalInspectionToolProvider.kt index 22e314567..fa519fe58 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliLocalInspectionToolProvider.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliLocalInspectionToolProvider.kt @@ -20,7 +20,6 @@ import com.alibaba.p3c.idea.inspection.standalone.AliAccessStaticViaInstanceInsp import com.alibaba.p3c.idea.inspection.standalone.AliDeprecationInspection import com.alibaba.p3c.idea.inspection.standalone.AliMissingOverrideAnnotationInspection import com.alibaba.p3c.idea.inspection.standalone.MapOrSetKeyShouldOverrideHashCodeEqualsInspection -import com.alibaba.p3c.pmd.I18nResources import com.alibaba.smartfox.idea.common.util.getService import com.beust.jcommander.internal.Lists import com.beust.jcommander.internal.Maps @@ -32,6 +31,7 @@ import com.intellij.psi.PsiCompiledFile import com.intellij.psi.PsiFile import com.intellij.psi.PsiImportList import com.intellij.psi.PsiJavaFile +import com.xenoamess.p3c.pmd.I18nResources import javassist.CannotCompileException import javassist.ClassClassPath import javassist.ClassPool @@ -40,7 +40,6 @@ import javassist.NotFoundException import net.sourceforge.pmd.Rule import net.sourceforge.pmd.RuleSet import net.sourceforge.pmd.RuleSetFactory -import net.sourceforge.pmd.RuleSetNotFoundException import net.sourceforge.pmd.RuleSets import javax.annotation.Generated @@ -67,9 +66,9 @@ class AliLocalInspectionToolProvider : InspectionToolProvider { class RuleInfo(var rule: Rule, var shouldInspectChecker: ShouldInspectChecker) companion object { - val ruleInfoMap: MutableMap = Maps.newHashMap() + val ruleInfoMap: MutableMap = Maps.newHashMap() private val LOGGER = Logger.getInstance(AliLocalInspectionToolProvider::class.java) - val ruleNames: MutableList = Lists.newArrayList()!! + val ruleNames: MutableList = Lists.newArrayList()!! private val CLASS_LIST = Lists.newArrayList>() private val nativeInspectionToolClass = arrayListOf>( AliMissingOverrideAnnotationInspection::class.java, @@ -139,7 +138,7 @@ class AliLocalInspectionToolProvider : InspectionToolProvider { private fun initPmdInspection() { for (ri in newRuleInfos()) { this.ruleNames.add(ri.rule.name) - ruleInfoMap.put(ri.rule.name, ri) + ruleInfoMap[ri.rule.name] = ri } val pool = ClassPool.getDefault() pool.insertClassPath(ClassClassPath(DelegatePmdInspection::class.java)) @@ -199,8 +198,8 @@ class AliLocalInspectionToolProvider : InspectionToolProvider { ruleSet.rules.mapTo(result) { RuleInfo(it, shouldInspectChecker) } - } catch (e: RuleSetNotFoundException) { - LOGGER.error(String.format("rule set %s not found for", ruleSetName)) + } catch (e: Exception) { + LOGGER.error(String.format("rule set %s load failed for", ruleSetName)) } return result diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliLongLiteralsEndingWithLowercaseLInspection.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliLongLiteralsEndingWithLowercaseLInspection.kt index c1fa74620..8fe49de6a 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliLongLiteralsEndingWithLowercaseLInspection.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliLongLiteralsEndingWithLowercaseLInspection.kt @@ -33,6 +33,7 @@ import com.siyeh.ig.numeric.LongLiteralsEndingWithLowercaseLInspection */ class AliLongLiteralsEndingWithLowercaseLInspection : LongLiteralsEndingWithLowercaseLInspection, AliBaseInspection { constructor() + /** * For Javassist */ diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliPmdInspection.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliPmdInspection.kt index a6731bead..846cecf11 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliPmdInspection.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliPmdInspection.kt @@ -99,7 +99,7 @@ class AliPmdInspection(private val ruleName: String) : LocalInspectionTool(), override fun getShortName(): String { - var shortName = "Alibaba" + ruleName + var shortName = "Alibaba$ruleName" val index = shortName.lastIndexOf("Rule") if (index > NumberConstants.INDEX_0) { shortName = shortName.substring(NumberConstants.INDEX_0, index) 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 6b57f75e3..3ede1be59 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 @@ -21,7 +21,7 @@ import com.alibaba.p3c.idea.pmd.AliPmdProcessor import com.alibaba.p3c.idea.util.DocumentUtils.calculateLineStart import com.alibaba.p3c.idea.util.DocumentUtils.calculateRealOffset import com.alibaba.p3c.idea.util.ProblemsUtils -import com.alibaba.p3c.pmd.lang.java.rule.comment.RemoveCommentedCodeRule +import com.xenoamess.p3c.pmd.lang.java.rule.comment.RemoveCommentedCodeRule import com.beust.jcommander.internal.Lists import com.google.common.cache.Cache import com.google.common.cache.CacheBuilder @@ -43,9 +43,9 @@ import java.util.concurrent.TimeUnit * @date 2016/12/13 */ class AliPmdInspectionInvoker( - private val psiFile: PsiFile, - private val manager: InspectionManager, - private val rule: Rule + private val psiFile: PsiFile, + private val manager: InspectionManager, + private val rule: Rule ) { private val logger = Logger.getInstance(javaClass) @@ -75,9 +75,12 @@ class AliPmdInspectionInvoker( } val problemDescriptors = Lists.newArrayList(violations.size) for (rv in violations) { - val virtualFile = LocalFileSystem.getInstance().findFileByPath(rv.filename) ?: continue - val psiFile = PsiManager.getInstance(manager.project).findFile(virtualFile) ?: continue - val document = FileDocumentManager.getInstance().getDocument(virtualFile) ?: continue + val virtualFile = LocalFileSystem.getInstance().findFileByPath(rv.filename) + ?: continue + val psiFile = PsiManager.getInstance(manager.project).findFile(virtualFile) + ?: continue + val document = FileDocumentManager.getInstance().getDocument(virtualFile) + ?: continue val offsets = if (rv.rule.name == RemoveCommentedCodeRule::class.java.simpleName) { Offsets( @@ -96,8 +99,14 @@ class AliPmdInspectionInvoker( "${rv.description} (line ${rv.beginLine})" } val problemDescriptor = ProblemsUtils.createProblemDescriptorForPmdRule( - psiFile, manager, - isOnTheFly, rv.rule.name, errorMessage, offsets.start, offsets.end, rv.beginLine + psiFile, + manager, + isOnTheFly, + rv.rule.name, + errorMessage, + offsets.start, + offsets.end, + rv.beginLine ) ?: continue problemDescriptors.add(problemDescriptor) } @@ -113,8 +122,10 @@ class AliPmdInspectionInvoker( } fun invokeInspection( - psiFile: PsiFile?, manager: InspectionManager, rule: Rule, - isOnTheFly: Boolean + psiFile: PsiFile?, + manager: InspectionManager, + rule: Rule, + isOnTheFly: Boolean ): Array? { if (psiFile == null) { return null diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliWrapperTypeEqualityInspection.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliWrapperTypeEqualityInspection.kt index 25ac033c5..d549025ee 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliWrapperTypeEqualityInspection.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliWrapperTypeEqualityInspection.kt @@ -113,7 +113,7 @@ class AliWrapperTypeEqualityInspection : BaseInspection, AliBaseInspection { return true } return TypeUtils.expressionHasTypeOrSubtype(expression, CommonClassNames.JAVA_LANG_BOOLEAN) - || TypeUtils.expressionHasTypeOrSubtype(expression, CommonClassNames.JAVA_LANG_CHARACTER) + || TypeUtils.expressionHasTypeOrSubtype(expression, CommonClassNames.JAVA_LANG_CHARACTER) } private fun hasNumberType(expression: PsiExpression): Boolean { @@ -126,13 +126,13 @@ class AliWrapperTypeEqualityInspection : BaseInspection, AliBaseInspection { } private class ArrayEqualityFix(private val deepEquals: Boolean, private val familyName: String) : - InspectionGadgetsFix() { + InspectionGadgetsFix() { override fun getName(): String { - if (deepEquals) { - return "$replaceWith 'Arrays.deepEquals()'" + return if (deepEquals) { + "$replaceWith 'Arrays.deepEquals()'" } else { - return "$replaceWith 'Arrays.equals()'" + "$replaceWith 'Arrays.equals()'" } } @@ -145,6 +145,7 @@ class AliWrapperTypeEqualityInspection : BaseInspection, AliBaseInspection { val element = descriptor.psiElement val parent = element.parent as? PsiBinaryExpression ?: return val tokenType = parent.operationTokenType + @NonNls val newExpressionText = StringBuilder() if (JavaTokenType.NE == tokenType) { @@ -163,14 +164,15 @@ class AliWrapperTypeEqualityInspection : BaseInspection, AliBaseInspection { newExpressionText.append(rhs.text) newExpressionText.append(')') PsiReplacementUtil.replaceExpressionAndShorten( - parent, - newExpressionText.toString() + parent, + newExpressionText.toString() ) } } override fun manualBuildFix(psiElement: PsiElement, isOnTheFly: Boolean): LocalQuickFix? { - val expression = psiElement.parent as? PsiBinaryExpression ?: return null + val expression = psiElement.parent as? PsiBinaryExpression + ?: return null val rhs = expression.rOperand ?: return null val lhs = expression.lOperand val lhsType = lhs.type diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/DelegateLocalInspectionTool.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/DelegateLocalInspectionTool.kt index b199f4a03..18e161bcf 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/DelegateLocalInspectionTool.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/DelegateLocalInspectionTool.kt @@ -46,9 +46,10 @@ class DelegateLocalInspectionTool : LocalInspectionTool(), AliBaseInspection { } override fun checkFile( - file: PsiFile, manager: InspectionManager, - isOnTheFly: Boolean - ): Array? { + file: PsiFile, + manager: InspectionManager, + isOnTheFly: Boolean + ): Array? { return localInspectionTool.checkFile(file, manager, isOnTheFly) } @@ -87,8 +88,9 @@ class DelegateLocalInspectionTool : LocalInspectionTool(), AliBaseInspection { } override fun buildVisitor( - holder: ProblemsHolder, isOnTheFly: Boolean, - session: LocalInspectionToolSession + holder: ProblemsHolder, + isOnTheFly: Boolean, + session: LocalInspectionToolSession ): PsiElementVisitor { if (!AliLocalInspectionToolProvider.javaShouldInspectChecker.shouldInspect(holder.file)) { return PsiElementVisitor.EMPTY_VISITOR diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/DelegatePmdInspection.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/DelegatePmdInspection.kt index 910bd2534..82fdb3c5c 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/DelegatePmdInspection.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/DelegatePmdInspection.kt @@ -42,8 +42,11 @@ class DelegatePmdInspection : LocalInspectionTool(), AliBaseInspection, PmdRuleI return aliPmdInspection.runForWholeFile() } - override fun checkFile(file: PsiFile, manager: InspectionManager, - isOnTheFly: Boolean): Array? { + override fun checkFile( + file: PsiFile, + manager: InspectionManager, + isOnTheFly: Boolean + ): Array? { return aliPmdInspection.checkFile(file, manager, isOnTheFly) } diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/PmdRuleInspectionIdentify.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/PmdRuleInspectionIdentify.kt index b84b5bd36..c3043f366 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/PmdRuleInspectionIdentify.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/PmdRuleInspectionIdentify.kt @@ -22,5 +22,4 @@ package com.alibaba.p3c.idea.inspection * @date 2017/03/16 6 */ -interface PmdRuleInspectionIdentify { -} \ No newline at end of file +interface PmdRuleInspectionIdentify \ No newline at end of file diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/RuleInspectionUtils.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/RuleInspectionUtils.kt index 3f0693d76..05d7b4e04 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/RuleInspectionUtils.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/RuleInspectionUtils.kt @@ -18,7 +18,7 @@ package com.alibaba.p3c.idea.inspection import com.alibaba.p3c.idea.config.P3cConfig import com.alibaba.p3c.idea.util.HighlightDisplayLevels import com.alibaba.p3c.idea.util.NumberConstants -import com.alibaba.p3c.pmd.I18nResources +import com.xenoamess.p3c.pmd.I18nResources import com.alibaba.smartfox.idea.common.util.getService import com.google.common.base.Joiner import com.google.common.collect.ImmutableMap @@ -59,7 +59,7 @@ object RuleInspectionUtils { cfg.getTemplate("StaticDescriptionTemplate.ftl") } - private val ruleSetsPrefix = "rulesets/" + private const val ruleSetsPrefix = "rulesets/" private val ruleStaticDescriptions: Map private val ruleMessages: Map @@ -92,10 +92,12 @@ object RuleInspectionUtils { } fun getHighlightDisplayLevel(rulePriority: RulePriority): HighlightDisplayLevel { - when (rulePriority) { - RulePriority.HIGH -> return HighlightDisplayLevels.BLOCKER - RulePriority.MEDIUM_HIGH -> return HighlightDisplayLevels.CRITICAL - else -> return HighlightDisplayLevels.MAJOR + return when (rulePriority) { + RulePriority.HIGH -> HighlightDisplayLevels.BLOCKER + RulePriority.MEDIUM_HIGH -> HighlightDisplayLevels.CRITICAL + RulePriority.MEDIUM -> HighlightDisplayLevels.MAJOR + RulePriority.MEDIUM_LOW -> HighlightDisplayLevels.WARNING + else -> HighlightDisplayLevels.WEAK_WARNING } } @@ -107,15 +109,14 @@ object RuleInspectionUtils { val writer = StringWriter() try { val map = Maps.newHashMap() - map.put("message", StringUtils.trimToEmpty(rule.message)) - map.put("description", StringUtils.trimToEmpty(rule.description)) + map["message"] = StringUtils.trimToEmpty(rule.message) + map["description"] = StringUtils.trimToEmpty(rule.description) val examples = rule.examples.map { - it?.trim { - c -> + it?.trim { c -> c == '\n' } } - map.put("examples", examples) + map["examples"] = examples staticDescriptionTemplate.process(map, writer) } catch (e: TemplateException) { logger.error(e) @@ -136,7 +137,7 @@ object RuleInspectionUtils { ruleSets.allRuleSets .asSequence() .flatMap { it.rules.asSequence() } - .forEach { map.put(it.name, it) } + .forEach { map[it.name] = it } return Lists.newArrayList(map.values) } catch (e: IOException) { logger.warn("no available alibaba rules") @@ -175,21 +176,21 @@ object RuleInspectionUtils { @Throws(IOException::class) private fun findRuleSetsFromJar(ruleSets: MutableList, url: URL) { - logger.info("start to find rule sets from jar " + url) + logger.info("start to find rule sets from jar $url") var path = URLDecoder.decode(url.path, StandardCharsets.UTF_8.name()) val index = path.lastIndexOf(URLUtil.JAR_SEPARATOR) if (index > NumberConstants.INDEX_0) { path = path.substring("file:".length, index) } val jarFile = JarFile(path) - logger.info("create jarFile for path " + path) + logger.info("create jarFile for path $path") val jarEntries = jarFile.entries() while (jarEntries.hasMoreElements()) { val jarEntry = jarEntries.nextElement() val subPath = jarEntry.name.replace(ruleSetsPrefix, "") if (ruleSetFilePattern.matcher(subPath).find()) { val resultPath = subPath.replace(".xml", "") - logger.info("get result rule set " + resultPath) + logger.info("get result rule set $resultPath") ruleSets.add(resultPath) } } diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/AliAccessStaticViaInstanceInspection.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/AliAccessStaticViaInstanceInspection.kt index ba5001e46..005167e69 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/AliAccessStaticViaInstanceInspection.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/AliAccessStaticViaInstanceInspection.kt @@ -26,19 +26,10 @@ import com.intellij.codeInsight.daemon.impl.analysis.HighlightUtil import com.intellij.codeInsight.daemon.impl.analysis.JavaHighlightUtil import com.intellij.codeInsight.daemon.impl.quickfix.AccessStaticViaInstanceFix import com.intellij.codeInsight.daemon.impl.quickfix.RemoveUnusedVariableUtil +import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemsHolder import com.intellij.codeInspection.accessStaticViaInstance.AccessStaticViaInstance -import com.intellij.psi.JavaElementVisitor -import com.intellij.psi.JavaResolveResult -import com.intellij.psi.PsiClass -import com.intellij.psi.PsiElement -import com.intellij.psi.PsiElementVisitor -import com.intellij.psi.PsiMember -import com.intellij.psi.PsiModifier -import com.intellij.psi.PsiPackage -import com.intellij.psi.PsiReferenceExpression -import com.intellij.psi.PsiSubstitutor -import java.util.ArrayList +import com.intellij.psi.* /** * @author caikang @@ -48,6 +39,7 @@ class AliAccessStaticViaInstanceInspection : AccessStaticViaInstance, AliBaseIns val messageKey = "com.alibaba.p3c.idea.inspection.standalone.AliAccessStaticViaInstanceInspection" constructor() + /** * For Javassist */ @@ -69,16 +61,12 @@ class AliAccessStaticViaInstanceInspection : AccessStaticViaInstance, AliBaseIns return "AliAccessStaticViaInstance" } - override fun createAccessStaticViaInstanceFix(expr: PsiReferenceExpression, - onTheFly: Boolean, - result: JavaResolveResult): AccessStaticViaInstanceFix { - return object : AccessStaticViaInstanceFix(expr, result, onTheFly) { + override fun createAccessStaticViaInstanceFix( + expr: PsiReferenceExpression, + result: JavaResolveResult + ): LocalQuickFix { + val accessStaticViaInstanceFix : AccessStaticViaInstanceFix = object : AccessStaticViaInstanceFix(expr, result) { val fixKey = "com.alibaba.p3c.idea.quickfix.standalone.AliAccessStaticViaInstanceInspection" - internal val text = calcText(result.element as PsiMember, result.substitutor) - - override fun getText(): String { - return text - } private fun calcText(member: PsiMember, substitutor: PsiSubstitutor): String { val aClass = member.containingClass ?: return "" @@ -93,6 +81,7 @@ class AliAccessStaticViaInstanceInspection : AccessStaticViaInstance, AliBaseIns } } } + return LocalQuickFix.from(accessStaticViaInstanceFix) as LocalQuickFix } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { @@ -107,9 +96,17 @@ class AliAccessStaticViaInstanceInspection : AccessStaticViaInstance, AliBaseIns return HighlightDisplayLevels.BLOCKER } - private fun checkAccessStaticMemberViaInstanceReference(expr: PsiReferenceExpression, holder: ProblemsHolder, - onTheFly: Boolean) { - val result = expr.advancedResolve(false) + private fun checkAccessStaticMemberViaInstanceReference( + expr: PsiReferenceExpression, + holder: ProblemsHolder, + onTheFly: Boolean + ) { + val result:JavaResolveResult; + try { + result = expr.advancedResolve(false) + } catch (e: Exception) { + return + } val resolved = result.element as? PsiMember ?: return val qualifierExpression = expr.qualifierExpression ?: return @@ -129,12 +126,12 @@ class AliAccessStaticViaInstanceInspection : AccessStaticViaInstance, AliBaseIns "${JavaHighlightUtil.formatType(qualifierExpression.type)}.${HighlightMessageUtil.getSymbolName( resolved, result.substitutor)}") if (!onTheFly) { - if (RemoveUnusedVariableUtil.checkSideEffects(qualifierExpression, null, ArrayList())) { + if (RemoveUnusedVariableUtil.checkSideEffects(qualifierExpression, null, ArrayList())) { holder.registerProblem(expr, description) return } } - holder.registerProblem(expr, description, createAccessStaticViaInstanceFix(expr, onTheFly, result)) + holder.registerProblem(expr, description, createAccessStaticViaInstanceFix(expr, result)) } } 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 78532cc2a..a4f7eea9a 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 @@ -40,6 +40,7 @@ class AliDeprecationInspection : DeprecationInspection, AliBaseInspection { private val messageKey = "com.alibaba.p3c.idea.inspection.standalone.AliDeprecationInspection" constructor() + /** * For Javassist */ @@ -87,40 +88,82 @@ class AliDeprecationInspection : DeprecationInspection, AliBaseInspection { class DeprecationInspectionProblemsHolder(private val holder: ProblemsHolder, onTheFly: Boolean) : ProblemsHolder( holder.manager, holder.file, onTheFly) { - override fun registerProblem(psiElement: PsiElement, + override fun registerProblem( + psiElement: PsiElement, @Nls descriptionTemplate: String, - fixes: Array?) { - holder.registerProblem(psiElement, getMessage(descriptionTemplate), *(fixes ?: emptyArray())) + fixes: Array? + ) { + holder.registerProblem( + psiElement, + getMessage(descriptionTemplate), + *(fixes ?: emptyArray()) + ) } - override fun registerProblem(psiElement: PsiElement, + override fun registerProblem( + psiElement: PsiElement, @Nls descriptionTemplate: String, - highlightType: ProblemHighlightType, fixes: Array?) { - holder.registerProblem(psiElement, getMessage(descriptionTemplate), highlightType, *(fixes ?: emptyArray())) + highlightType: ProblemHighlightType, + fixes: Array? + ) { + holder.registerProblem( + psiElement, + getMessage(descriptionTemplate), + highlightType, + *(fixes ?: emptyArray()) + ) } - override fun registerProblem(reference: PsiReference, descriptionTemplate: String, - highlightType: ProblemHighlightType) { + override fun registerProblem( + reference: PsiReference, + descriptionTemplate: String, + highlightType: ProblemHighlightType + ) { holder.registerProblem(reference, getMessage(descriptionTemplate), highlightType) } - override fun registerProblemForReference(reference: PsiReference, - highlightType: ProblemHighlightType, descriptionTemplate: String, - fixes: Array?) { - holder.registerProblemForReference(reference, highlightType, getMessage(descriptionTemplate), - *(fixes ?: emptyArray())) + override fun registerProblemForReference( + reference: PsiReference, + highlightType: ProblemHighlightType, + descriptionTemplate: String, + fixes: Array? + ) { + holder.registerProblemForReference( + reference, + highlightType, + getMessage(descriptionTemplate), + *(fixes ?: emptyArray()) + ) } - override fun registerProblem(psiElement: PsiElement, rangeInElement: TextRange?, - message: String, fixes: Array?) { - holder.registerProblem(psiElement, rangeInElement, getMessage(message), *(fixes ?: emptyArray())) + override fun registerProblem( + psiElement: PsiElement, + rangeInElement: TextRange?, + message: String, + fixes: Array? + ) { + holder.registerProblem( + psiElement, + rangeInElement, + getMessage(message), + *(fixes ?: emptyArray()) + ) } - override fun registerProblem(psiElement: PsiElement, message: String, - highlightType: ProblemHighlightType, rangeInElement: TextRange?, - fixes: Array?) { - holder.registerProblem(psiElement, getMessage(message), highlightType, rangeInElement, - *(fixes ?: emptyArray())) + override fun registerProblem( + psiElement: PsiElement, + message: String, + highlightType: ProblemHighlightType, + rangeInElement: TextRange?, + fixes: Array? + ) { + holder.registerProblem( + psiElement, + getMessage(message), + highlightType, + rangeInElement, + *(fixes ?: emptyArray()) + ) } private fun getMessage(msg: String): String { 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 9b4d0070d..22a1084b3 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 @@ -44,6 +44,7 @@ class AliMissingOverrideAnnotationInspection : MissingOverrideAnnotationInspecti private val messageKey = "com.alibaba.p3c.idea.inspection.standalone.AliMissingOverrideAnnotationInspection" constructor() + /** * For Javassist */ @@ -64,10 +65,17 @@ class AliMissingOverrideAnnotationInspection : MissingOverrideAnnotationInspecti override fun createOptionsPanel(): JComponent? = null - 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")) + override protected fun buildFix(vararg infos: Any): InspectionGadgetsFix? { + val fix : LocalQuickFix + try { + fix = super.buildFix(*infos) ?: return null + } catch (e: Exception){ + return null; + } + return DecorateInspectionGadgetsFix( + fix, + P3cBundle.getMessage("com.alibaba.p3c.idea.quickfix.standalone.AliMissingOverrideAnnotationInspection") + ) } override fun manualBuildFix(psiElement: PsiElement, isOnTheFly: Boolean): LocalQuickFix? = buildFix(psiElement) @@ -98,12 +106,18 @@ class AliMissingOverrideAnnotationInspection : MissingOverrideAnnotationInspecti if (!isJdk6Override(method, methodClass) && !isJdk5Override(method, methodClass)) { return } - if (ignoreObjectMethods && (MethodUtils.isHashCode(method) || - MethodUtils.isEquals(method) || - MethodUtils.isToString(method))) { + if (ignoreObjectMethods + && + (MethodUtils.isHashCode(method) + || + MethodUtils.isEquals(method) + || + MethodUtils.isToString(method) + ) + ) { return } - registerMethodError(method) + this.registerMethodError(method, *arrayOf(method, true, true)) } private fun hasOverrideAnnotation(element: PsiModifierListOwner): Boolean { 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 6eea27134..3d07c4daa 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 @@ -33,6 +33,7 @@ import com.intellij.psi.PsiVariable import com.siyeh.ig.BaseInspection import com.siyeh.ig.BaseInspectionVisitor import org.jetbrains.annotations.NonNls +import java.util.Locale /** * @author caikang @@ -81,14 +82,14 @@ class MapOrSetKeyShouldOverrideHashCodeEqualsInspection : BaseInspection, AliBas override fun toString(): String { val string = super.toString() - return string[0] + string.substring(1).toLowerCase() + return string[0] + string.substring(1).lowercase() } } private class MapOrSetKeyVisitor : BaseInspectionVisitor() { private fun getClassType(aClass: PsiClass?): ClassType { - return isMapOrSet(aClass, Sets.newHashSet()) + return isMapOrSet(aClass, Sets.newHashSet()) } private fun isMapOrSet(aClass: PsiClass?, visitedClasses: MutableSet): ClassType { @@ -171,8 +172,8 @@ class MapOrSetKeyShouldOverrideHashCodeEqualsInspection : BaseInspection, AliBas companion object { - private val skipJdkPackageJava = "java." - private val skipJdkPackageJavax = "javax." + private const val skipJdkPackageJava = "java." + private const val skipJdkPackageJavax = "javax." private fun redefineHashCodeEquals(psiType: PsiType): Boolean { if (psiType !is PsiClassType) { 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 76557d40f..bee7f88e8 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 @@ -15,6 +15,7 @@ */ package com.alibaba.p3c.idea.pmd +import com.alibaba.p3c.idea.compatible.inspection.Inspections import com.alibaba.p3c.idea.component.AliProjectComponent import com.google.common.base.Throwables import com.intellij.openapi.application.ex.ApplicationUtil @@ -52,6 +53,7 @@ class AliPmdProcessor private constructor(val rule: Rule? = null, val ruleSets: } fun processFile(psiFile: PsiFile, isOnTheFly: Boolean): List { + Inspections.loadPatchConfigFile(psiFile.project) configuration.setSourceEncoding(psiFile.virtualFile.charset.name()) configuration.inputPaths = psiFile.virtualFile.canonicalPath val document = FileDocumentManager.getInstance().getDocument(psiFile.virtualFile) ?: return emptyList() 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 aae6148c8..985faca4c 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 @@ -26,6 +26,10 @@ 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 java.io.IOException +import java.io.InputStream +import java.io.InputStreamReader import java.io.Reader import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit.MILLISECONDS @@ -60,6 +64,15 @@ class SourceCodeProcessor( @Throws(PMDException::class) fun processSourceCode(sourceCode: Reader, ruleSets: RuleSets, ctx: RuleContext) { determineLanguage(ctx) + + // make sure custom XPath functions are initialized + Initializer.initialize() + + processSourceCodeWithoutCache(sourceCode, ruleSets, ctx) + } + + @Throws(PMDException::class) + private fun processSourceCodeWithoutCache(sourceCode: Reader, ruleSets: RuleSets, ctx: RuleContext) { try { ruleSets.start(ctx) processSource(sourceCode, ruleSets, ctx) @@ -143,6 +156,7 @@ class SourceCodeProcessor( val languageVersionHandler = languageVersion.languageVersionHandler val parser = PMD.parserFor(languageVersion, configuration) val rootNode = parse(ctx, sourceCode, parser) + resolveQualifiedNames(rootNode, languageVersionHandler) symbolFacade(rootNode, languageVersionHandler) val language = languageVersion.language usesDFA(languageVersion, rootNode, ruleSets, language) @@ -181,20 +195,25 @@ class SourceCodeProcessor( } private fun usesTypeResolution( - languageVersion: LanguageVersion, rootNode: Node, ruleSets: RuleSets, - language: Language + 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) + .start(rootNode) } } } + private fun usesMultifile( - rootNode: Node, languageVersionHandler: LanguageVersionHandler, ruleSets: RuleSets, + rootNode: Node, + languageVersionHandler: LanguageVersionHandler, + ruleSets: RuleSets, language: Language ) { diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/index/InspectionDataSource.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/index/InspectionDataSource.kt index 10f95ae78..5ef958463 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/index/InspectionDataSource.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/index/InspectionDataSource.kt @@ -35,4 +35,8 @@ class InspectionDataSource(private val fileContent: FileContent) : DataSource { override fun getNiceFileName(shortNames: Boolean, inputFileName: String?): String { return fileContent.fileName } + + override fun close() { + // empty default implementation + } } diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/AliQuickFix.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/AliQuickFix.kt index ee7acc5c4..57e9ffba8 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/AliQuickFix.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/AliQuickFix.kt @@ -19,6 +19,7 @@ import com.intellij.codeInspection.LocalQuickFix import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys +import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.psi.JavaPsiFacade @@ -28,6 +29,7 @@ import com.intellij.psi.PsiIdentifier import com.intellij.psi.PsiLocalVariable import com.intellij.psi.PsiMember import com.intellij.psi.PsiParameter +import java.lang.reflect.Method /** * @@ -47,7 +49,11 @@ interface AliQuickFix : LocalQuickFix { companion object { const val groupName = "Ali QuickFix" - fun doQuickFix(newIdentifier: String, project: Project, psiIdentifier: PsiIdentifier) { + fun doQuickFix( + newIdentifier: String, + project: Project, + psiIdentifier: PsiIdentifier + ) { val offset = psiIdentifier.textOffset val cannotFix = psiIdentifier.parent !is PsiMember && !(psiIdentifier.parent is PsiLocalVariable || psiIdentifier.parent is PsiParameter) @@ -57,25 +63,43 @@ interface AliQuickFix : LocalQuickFix { val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return editor.caretModel.moveToOffset(psiIdentifier.textOffset) - val anAction = ActionManager.getInstance().getAction("RenameElement") val psiFile = psiIdentifier.containingFile + commitDocumentIfNeeded(psiFile, project) - val event = AnActionEvent.createFromDataContext("MainMenu", anAction.templatePresentation) { - when (it) { - CommonDataKeys.PROJECT.name -> project - CommonDataKeys.EDITOR.name -> editor - CommonDataKeys.PSI_FILE.name -> psiFile - CommonDataKeys.PSI_ELEMENT.name -> psiIdentifier.parent - else -> null - } - } + val psiFacade = JavaPsiFacade.getInstance(project) val factory = psiFacade.elementFactory - anAction.actionPerformed(event) + try { + val application = ApplicationManager.getApplication() + val isWriteThreadMethod: Method = + application.javaClass.getDeclaredMethod("isWriteThread") + val isWriteThread = isWriteThreadMethod.invoke(application) + if (!(isWriteThread as Boolean)) { + val anAction = + ActionManager.getInstance().getAction("RenameElement") + val event = AnActionEvent.createFromDataContext( + "MainMenu", + anAction.templatePresentation + ) { + when (it) { + CommonDataKeys.PROJECT.name -> project + CommonDataKeys.EDITOR.name -> editor + CommonDataKeys.PSI_FILE.name -> psiFile + CommonDataKeys.PSI_ELEMENT.name -> psiIdentifier.parent + else -> null + } + } + anAction.actionPerformed(event) + } + } catch (e: Exception) { + } finally { + } // origin PsiIdentifier is unavailable psiFile.findElementAt(offset)?.replace(factory.createIdentifier(newIdentifier)) + + commitDocumentIfNeeded(psiFile, project) } private fun commitDocumentIfNeeded(file: PsiFile?, project: Project) { diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/AvoidStartWithDollarAndUnderLineNamingQuickFix.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/AvoidStartWithDollarAndUnderLineNamingQuickFix.kt index 24e985962..a2c6eb170 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/AvoidStartWithDollarAndUnderLineNamingQuickFix.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/AvoidStartWithDollarAndUnderLineNamingQuickFix.kt @@ -19,7 +19,7 @@ import com.alibaba.p3c.idea.i18n.P3cBundle import com.intellij.codeInspection.ProblemDescriptor import com.intellij.openapi.project.Project import com.intellij.psi.PsiIdentifier -import org.apache.commons.lang3.StringUtils +import org.apache.commons.lang3.RegExUtils /** * @@ -40,7 +40,7 @@ object AvoidStartWithDollarAndUnderLineNamingQuickFix : AliQuickFix { override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val psiIdentifier = descriptor.psiElement as? PsiIdentifier ?: return val identifier = psiIdentifier.text - val resultName = StringUtils.replacePattern(identifier, "^[\$_]+", "") + val resultName = RegExUtils.replacePattern(identifier, "^[\$_]+", "") if (resultName.toLongOrNull() != null) { return } diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/ClassMustHaveAuthorQuickFix.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/ClassMustHaveAuthorQuickFix.kt index f9fb072ee..b676cac75 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/ClassMustHaveAuthorQuickFix.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/ClassMustHaveAuthorQuickFix.kt @@ -33,9 +33,11 @@ object ClassMustHaveAuthorQuickFix : InspectionGadgetsFix(), AliQuickFix { val tag = "@author ${System.getProperty("user.name") ?: System.getenv("USER")}" - override fun doFix(project: Project?, descriptor: ProblemDescriptor?) { + override fun doFix(project: Project, descriptor: ProblemDescriptor) { descriptor ?: return - val psiClass = descriptor.psiElement as? PsiClass ?: descriptor.psiElement?.parent as? PsiClass ?: return + val psiClass = descriptor.psiElement as? PsiClass + ?: descriptor.psiElement?.parent as? PsiClass + ?: return val document = psiClass.docComment val psiFacade = JavaPsiFacade.getInstance(project) diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/ConstantFieldShouldBeUpperCaseQuickFix.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/ConstantFieldShouldBeUpperCaseQuickFix.kt index 85da4f5ac..e294891a2 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/ConstantFieldShouldBeUpperCaseQuickFix.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/ConstantFieldShouldBeUpperCaseQuickFix.kt @@ -20,6 +20,7 @@ import com.google.common.base.Splitter import com.intellij.codeInspection.ProblemDescriptor import com.intellij.openapi.project.Project import com.intellij.psi.PsiIdentifier +import java.util.Locale /** * @@ -28,7 +29,7 @@ import com.intellij.psi.PsiIdentifier * @date 2017/02/28 */ object ConstantFieldShouldBeUpperCaseQuickFix : AliQuickFix { - val separator = '_' + const val separator = '_' override fun getName(): String { return P3cBundle.getMessage("com.alibaba.p3c.idea.quickfix.field.to.upperCaseWithUnderscore") @@ -40,7 +41,7 @@ object ConstantFieldShouldBeUpperCaseQuickFix : AliQuickFix { val list = Splitter.on(separator).trimResults().omitEmptyStrings().splitToList(identifier) val resultName = list.joinToString(separator.toString()) { - separateCamelCase(it).toUpperCase() + separateCamelCase(it).uppercase() } AliQuickFix.doQuickFix(resultName, project, psiIdentifier) diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/DecorateInspectionFix.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/DecorateInspectionFix.kt index 052bf560a..881aaf61c 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/DecorateInspectionFix.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/DecorateInspectionFix.kt @@ -15,6 +15,7 @@ */ package com.alibaba.p3c.idea.quickfix +import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.openapi.project.Project import com.siyeh.ig.InspectionGadgetsFix @@ -25,9 +26,11 @@ import com.siyeh.ig.InspectionGadgetsFix * @author caikang * @date 2017/03/02 */ -class DecorateInspectionGadgetsFix(val fix: InspectionGadgetsFix, - internal val name: String, - internal val familyName: String = name) : InspectionGadgetsFix() { +class DecorateInspectionGadgetsFix( + val fix: LocalQuickFix, + internal val name: String, + internal val familyName: String = name +) : InspectionGadgetsFix() { override fun getName(): String { return name } 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 579025d20..50b79b33f 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 @@ -45,11 +45,15 @@ object LowerCamelCaseVariableNamingQuickFix : AliQuickFix { } private fun toLowerCamelCase(identifier: String): String { - val list = Splitter.onPattern("[^a-z0-9A-Z]+").trimResults() - .omitEmptyStrings().split(identifier).toList() + val list = Splitter + .onPattern("[^a-z0-9A-Z]+") + .trimResults() + .omitEmptyStrings() + .split(identifier) + .toList() val result = list.mapIndexed { i, s -> val charArray = s.toCharArray() - charArray[0] = if (i == 0) charArray[0].toLowerCase() else charArray[0].toUpperCase() + charArray[0] = if (i == 0) charArray[0].lowercaseChar() else charArray[0].uppercaseChar() String(charArray) } return result.joinToString("") diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/DocumentUtils.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/DocumentUtils.kt index 54635e597..c41d86d7a 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/DocumentUtils.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/DocumentUtils.kt @@ -26,7 +26,7 @@ import com.intellij.openapi.util.TextRange 6 */ object DocumentUtils { - private val PMD_TAB_SIZE = 8 + private const val PMD_TAB_SIZE = 8 fun calculateRealOffset(document: Document, line: Int, pmdColumn: Int): Int { val maxLine = document.lineCount if (maxLine < line) { diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/HighlightDisplayLevels.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/HighlightDisplayLevels.kt index 4c42da961..e2d791266 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/HighlightDisplayLevels.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/HighlightDisplayLevels.kt @@ -27,4 +27,6 @@ object HighlightDisplayLevels { val BLOCKER = HighlightDisplayLevel(HighlightSeverities.BLOCKER, HighlightDisplayLevel.ERROR.icon) val CRITICAL = HighlightDisplayLevel(HighlightSeverities.CRITICAL, HighlightDisplayLevel.WARNING.icon) val MAJOR = HighlightDisplayLevel(HighlightSeverities.MAJOR, HighlightDisplayLevel.WEAK_WARNING.icon) + val WARNING = HighlightDisplayLevel(HighlightSeverities.WARNING, HighlightDisplayLevel.WEAK_WARNING.icon) + val WEAK_WARNING = HighlightDisplayLevel(HighlightSeverities.WEAK_WARNING, HighlightDisplayLevel.WEAK_WARNING.icon) } diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/HighlightInfoTypes.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/HighlightInfoTypes.kt index 16504ca8a..cd479ae26 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/HighlightInfoTypes.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/HighlightInfoTypes.kt @@ -31,4 +31,8 @@ object HighlightInfoTypes { CodeInsightColors.WARNINGS_ATTRIBUTES) val MAJOR: HighlightInfoType = HighlightInfoType.HighlightInfoTypeImpl(HighlightSeverities.MAJOR, CodeInsightColors.WEAK_WARNING_ATTRIBUTES) + val WARNING: HighlightInfoType = HighlightInfoType.HighlightInfoTypeImpl(HighlightSeverities.WARNING, + CodeInsightColors.WEAK_WARNING_ATTRIBUTES) + val WEAK_WARNING: HighlightInfoType = HighlightInfoType.HighlightInfoTypeImpl(HighlightSeverities.WEAK_WARNING, + CodeInsightColors.WEAK_WARNING_ATTRIBUTES) } diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/HighlightSeverities.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/HighlightSeverities.kt index 5f75753ba..80017e281 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/HighlightSeverities.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/HighlightSeverities.kt @@ -24,16 +24,14 @@ import com.intellij.lang.annotation.HighlightSeverity * @date 2017/02/04 */ object HighlightSeverities { + val BLOCKER = HighlightSeverity("BLOCKER", 399) + + val CRITICAL = HighlightSeverity("CRITICAL", 398) + val MAJOR = HighlightSeverity("MAJOR", 397) + val WARNING = HighlightSeverity("WARNING", 396) - /** - * The standard severity level for warning annotations. - */ - val CRITICAL = HighlightSeverity("CRITICAL", 398) + val WEAK_WARNING = HighlightSeverity("WEAK_WARNING", 395) - /** - * The standard severity level for error annotations. - */ - val BLOCKER = HighlightSeverity("BLOCKER", 399) } diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/NumberConstants.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/NumberConstants.kt index b71c8db79..1dd8cdc3e 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/NumberConstants.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/NumberConstants.kt @@ -20,10 +20,10 @@ package com.alibaba.p3c.idea.util * @date 2016/12/28 */ object NumberConstants { - val INTEGER_SIZE_OR_LENGTH_0 = 0 - val INTEGER_SIZE_OR_LENGTH_1 = 1 - val INTEGER_SIZE_OR_LENGTH_2 = 2 + const val INTEGER_SIZE_OR_LENGTH_0 = 0 + const val INTEGER_SIZE_OR_LENGTH_1 = 1 + const val INTEGER_SIZE_OR_LENGTH_2 = 2 - val INDEX_0 = 0 - val INDEX_1 = 1 + const val INDEX_0 = 0 + const val INDEX_1 = 1 } diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/ObjectConstants.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/ObjectConstants.kt index b54ea3fcf..c527c2a67 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/ObjectConstants.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/ObjectConstants.kt @@ -20,11 +20,11 @@ package com.alibaba.p3c.idea.util * @date 2016/12/28 */ object ObjectConstants { - val METHOD_NAME_EQUALS = "equals" - val METHOD_NAME_HASHCODE = "hashCode" - val METHOD_NAME_ADD = "add" - val METHOD_NAME_PUT = "put" - val CLASS_LITERAL = "class" - val INTERFACE_LITERAL = "interface" - val ENUM_LITERAL = "enum" + const val METHOD_NAME_EQUALS = "equals" + const val METHOD_NAME_HASHCODE = "hashCode" + const val METHOD_NAME_ADD = "add" + const val METHOD_NAME_PUT = "put" + const val CLASS_LITERAL = "class" + const val INTERFACE_LITERAL = "interface" + const val ENUM_LITERAL = "enum" } diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/ProblemsUtils.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/ProblemsUtils.kt index 4c74a1545..6159aefef 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/ProblemsUtils.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/ProblemsUtils.kt @@ -15,7 +15,7 @@ */ package com.alibaba.p3c.idea.util -import com.alibaba.p3c.pmd.lang.java.rule.comment.AvoidCommentBehindStatementRule +import com.xenoamess.p3c.pmd.lang.java.rule.comment.AvoidCommentBehindStatementRule import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor @@ -42,13 +42,21 @@ import com.intellij.psi.impl.source.tree.ElementType object ProblemsUtils { private val highlightLineRules = setOf(AvoidCommentBehindStatementRule::class.java.simpleName) - fun createProblemDescriptorForPmdRule(psiFile: PsiFile, manager: InspectionManager, isOnTheFly: Boolean, - ruleName: String, desc: String, start: Int, end: Int, + fun createProblemDescriptorForPmdRule( + psiFile: PsiFile, + manager: InspectionManager, + isOnTheFly: Boolean, + ruleName: String, + desc: String, + start: Int, + end: Int, checkLine: Int = 0, quickFix: (PsiElement) -> LocalQuickFix? = { QuickFixes.getQuickFix(ruleName, isOnTheFly) - }): ProblemDescriptor? { - val document = FileDocumentManager.getInstance().getDocument(psiFile.virtualFile) ?: return null + } + ): ProblemDescriptor? { + val document = FileDocumentManager.getInstance().getDocument(psiFile.virtualFile) + ?: return null if (highlightLineRules.contains(ruleName) && checkLine <= document.lineCount) { val lineNumber = if (start >= document.textLength) { document.lineCount - 1 @@ -82,9 +90,15 @@ object ProblemsUtils { } endElement = psiElement } - return manager.createProblemDescriptor(psiElement, endElement, - desc, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly, - quickFix(psiElement)) + val localQuickFix = quickFix(psiElement) ?: return null + return manager.createProblemDescriptor( + psiElement, + endElement, + desc, + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + isOnTheFly, + localQuickFix + ) } private fun getEndElement(psiFile: PsiFile, psiElement: PsiElement, endOffset: Int): PsiElement { @@ -113,9 +127,14 @@ object ProblemsUtils { if (psiElement == null) { return null } - if (psiElement is PsiKeyword && psiElement.text != null && (ObjectConstants.CLASS_LITERAL == psiElement.text - || ObjectConstants.INTERFACE_LITERAL == psiElement.text - || ObjectConstants.ENUM_LITERAL == psiElement.text) && psiElement.parent is PsiClass) { + if (psiElement is PsiKeyword + && psiElement.text != null + && (ObjectConstants.CLASS_LITERAL == psiElement.text + || ObjectConstants.INTERFACE_LITERAL == psiElement.text + || ObjectConstants.ENUM_LITERAL == psiElement.text + ) + && psiElement.parent is PsiClass + ) { val parent = psiElement.parent as PsiClass val identifier = parent.nameIdentifier return identifier ?: psiElement @@ -123,14 +142,25 @@ object ProblemsUtils { return psiElement } - private fun createTextRangeProblem(manager: InspectionManager, textRange: TextRange, isOnTheFly: Boolean, - psiFile: PsiFile, ruleName: String, desc: String, + private fun createTextRangeProblem( + manager: InspectionManager, + textRange: TextRange, + isOnTheFly: Boolean, + psiFile: PsiFile, + ruleName: String, + desc: String, quickFix: () -> LocalQuickFix? = { QuickFixes.getQuickFix(ruleName, isOnTheFly) - }): ProblemDescriptor { - + } + ): ProblemDescriptor? { + val localQuickFix = quickFix(); + if (localQuickFix == null) { + return manager.createProblemDescriptor(psiFile, textRange, + desc, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + isOnTheFly) + } return manager.createProblemDescriptor(psiFile, textRange, desc, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - isOnTheFly, quickFix()) + isOnTheFly, localQuickFix) } } diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/vcs/AliCodeAnalysisCheckinHandler.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/vcs/AliCodeAnalysisCheckinHandler.kt index df369b133..97fe31a49 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/vcs/AliCodeAnalysisCheckinHandler.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/vcs/AliCodeAnalysisCheckinHandler.kt @@ -64,8 +64,8 @@ import javax.swing.JPanel * @date 2017/05/04 */ class AliCodeAnalysisCheckinHandler( - private val myProject: Project, - private val myCheckinPanel: CheckinProjectPanel + private val myProject: Project, + private val myCheckinPanel: CheckinProjectPanel ) : CheckinHandler() { private val dialogTitle = "Alibaba Code Analyze" private val cancelText = "&Cancel" @@ -107,18 +107,22 @@ class AliCodeAnalysisCheckinHandler( } override fun beforeCheckin( - executor: CommitExecutor?, - additionalDataConsumer: PairConsumer + executor: CommitExecutor?, + additionalDataConsumer: PairConsumer ): CheckinHandler.ReturnResult { if (!getSettings().analysisBeforeCheckin) { return CheckinHandler.ReturnResult.COMMIT } if (DumbService.getInstance(myProject).isDumb) { if (Messages.showOkCancelDialog( - myProject, - "Code analysis is impossible until indices are up-to-date", dialogTitle, - waitingText, commitText, null - ) == Messages.OK + myProject, + "Code analysis is impossible until indices are up-to-date", + dialogTitle, + waitingText, + commitText, + null + ) + == Messages.OK ) { return CheckinHandler.ReturnResult.CANCEL } @@ -135,9 +139,14 @@ class AliCodeAnalysisCheckinHandler( return CheckinHandler.ReturnResult.COMMIT } if (Messages.showOkCancelDialog( - myProject, "Found suspicious code,continue commit?", - dialogTitle, commitText, cancelText, null - ) == Messages.OK + myProject, + "Found suspicious code,continue commit?", + dialogTitle, + commitText, + cancelText, + null + ) + == Messages.OK ) { return CheckinHandler.ReturnResult.COMMIT } else { @@ -149,8 +158,8 @@ class AliCodeAnalysisCheckinHandler( fun doAnalysis(project: Project, virtualFiles: Array) { val managerEx = InspectionManager.getInstance(project) as InspectionManagerEx val analysisScope = AnalysisScope( - project, - ArrayList(Arrays.asList(*virtualFiles)) + project, + ArrayList(listOf(*virtualFiles)) ) val tools = Inspections.aliInspections(project) { it.tool is AliBaseInspection } AliInspectionAction.createContext(tools, managerEx, null, false, analysisScope) @@ -161,7 +170,7 @@ class AliCodeAnalysisCheckinHandler( ApplicationManager.getApplication().assertIsDispatchThread() PsiDocumentManager.getInstance(myProject).commitAllDocuments() if (ApplicationManager.getApplication().isWriteAccessAllowed) throw RuntimeException( - "Must not run under write action" + "Must not run under write action" ) val result = AtomicBoolean(false) val exception = Ref.create() @@ -173,9 +182,11 @@ class AliCodeAnalysisCheckinHandler( val inspectionManager = InspectionManager.getInstance(project) val psiManager = PsiManager.getInstance(project) val count = AtomicInteger(0) - val hasViolation = virtualFiles.asSequence().any { file -> + val hasViolation = virtualFiles.asSequence().any { + file -> ApplicationManager.getApplication().runReadAction(Computable { - val psiFile = psiManager.findFile(file) ?: return@Computable false + val psiFile = psiManager.findFile(file) + ?: return@Computable false val curCount = count.incrementAndGet() progress.text = file.canonicalPath progress.fraction = curCount.toDouble() / virtualFiles.size.toDouble() diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/job/P3cMutex.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/activity/AliBaseApplicationStartupActivity.kt similarity index 64% rename from eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/job/P3cMutex.kt rename to idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/activity/AliBaseApplicationStartupActivity.kt index 8dab560a6..13825f868 100644 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/job/P3cMutex.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/activity/AliBaseApplicationStartupActivity.kt @@ -13,22 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.smartfox.eclipse.job +package com.alibaba.smartfox.idea.common.activity -import org.eclipse.core.runtime.jobs.ISchedulingRule +import com.intellij.openapi.startup.StartupActivity /** * * * @author caikang - * @date 2017/06/14 + * @date 2017/05/11 */ -object P3cMutex : ISchedulingRule { - override fun contains(rule: ISchedulingRule?): Boolean { - return isConflicting(rule) - } - - override fun isConflicting(rule: ISchedulingRule?): Boolean { - return rule == this - } -} \ No newline at end of file +interface AliBaseApplicationStartupActivity : StartupActivity \ No newline at end of file diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/util/BalloonNotifications.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/util/BalloonNotifications.kt index 6963bbbba..bf96657e9 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/util/BalloonNotifications.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/util/BalloonNotifications.kt @@ -23,6 +23,7 @@ import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.ui.Messages +import org.apache.http.MethodNotSupportedException import java.awt.Component import java.net.UnknownHostException @@ -33,12 +34,12 @@ import java.net.UnknownHostException * @date 2017/05/08 */ object BalloonNotifications { - val displayId = "SmartFox Intellij IDEA Balloon Notification" - val balloonGroup = NotificationGroup(displayId, NotificationDisplayType.BALLOON, true) + const val displayId = "SmartFox Intellij IDEA Balloon Notification" + val balloonGroup = buildNotificationGroup(displayId, NotificationDisplayType.BALLOON, true) - val stickyBalloonDisplayId = "SmartFox Intellij IDEA Notification" - val stickyBalloonGroup = NotificationGroup(stickyBalloonDisplayId, NotificationDisplayType.STICKY_BALLOON, true) - val TITLE = "SmartFox Intellij IDEA Plugin" + const val stickyBalloonDisplayId = "SmartFox Intellij IDEA Notification" + val stickyBalloonGroup = buildNotificationGroup(stickyBalloonDisplayId, NotificationDisplayType.STICKY_BALLOON, true) + const val TITLE = "SmartFox Intellij IDEA Plugin" fun showInfoDialog(component: Component, title: String, message: String) { Messages.showInfoMessage(component, message, title) @@ -56,29 +57,29 @@ object BalloonNotifications { } fun showSuccessNotification(message: String, project: Project? = ProjectManager.getInstance().defaultProject, - title: String = TITLE, sticky: Boolean = false) { + title: String = TITLE, sticky: Boolean = false) { showNotification(message, project, title, NotificationType.INFORMATION, null, sticky) } fun showWarnNotification(message: String, project: Project? = ProjectManager.getInstance().defaultProject, - title: String = TITLE, sticky: Boolean = false) { + title: String = TITLE, sticky: Boolean = false) { showNotification(message, project, title, NotificationType.WARNING, null, sticky) } fun showErrorNotification(message: String, project: Project? = ProjectManager.getInstance().defaultProject, - title: String = TITLE, sticky: Boolean = false) { + title: String = TITLE, sticky: Boolean = false) { showNotification(message, project, title, NotificationType.ERROR, null, sticky) } fun showSuccessNotification(message: String, project: Project?, - notificationListener: NotificationListener, title: String = TITLE, sticky: Boolean = false) { + notificationListener: NotificationListener, title: String = TITLE, sticky: Boolean = false) { showNotification(message, project, title, NotificationType.INFORMATION, notificationListener, sticky) } fun showNotification(message: String, project: Project? = ProjectManager.getInstance().defaultProject, - title: String = TITLE, - notificationType: NotificationType = NotificationType.INFORMATION, - notificationListener: NotificationListener? = null, sticky: Boolean = false) { + title: String = TITLE, + notificationType: NotificationType = NotificationType.INFORMATION, + notificationListener: NotificationListener? = null, sticky: Boolean = false) { val group = if (sticky) { stickyBalloonGroup } else { @@ -100,7 +101,8 @@ object BalloonNotifications { } object LogNotifications { - val group = NotificationGroup(BalloonNotifications.displayId, NotificationDisplayType.NONE, true) + + val group = buildNotificationGroup(displayId = BalloonNotifications.displayId, displayType = NotificationDisplayType.NONE, isLogByDefault = true) fun log(message: String, project: Project? = ProjectManager.getInstance().defaultProject, title: String = BalloonNotifications.TITLE, @@ -109,3 +111,19 @@ object LogNotifications { group.createNotification(title, message, notificationType, notificationListener).notify(project) } } + + +fun buildNotificationGroup(displayId: String, displayType: NotificationDisplayType, isLogByDefault: Boolean): NotificationGroup { + val notificationGroupClass = Class.forName("com.intellij.notification.NotificationGroup") + notificationGroupClass.constructors.forEach { + if (it.parameters.size == 3) { + try { + return it.newInstance(displayId, displayType, isLogByDefault) + as NotificationGroup + } catch (e: Exception) { + System.err.println(e) + } + } + } + throw MethodNotSupportedException("cannot find a suitable constructor for NotificationGroup who accepts [String,NotificationDisplayType,Boolean]") +} diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/util/CommonExtensions.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/util/CommonExtensions.kt index 7b77198fd..3aecc2cbd 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/util/CommonExtensions.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/util/CommonExtensions.kt @@ -15,7 +15,7 @@ */ package com.alibaba.smartfox.idea.common.util -import com.intellij.openapi.components.ServiceManager +import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.Project /** @@ -25,9 +25,9 @@ import com.intellij.openapi.project.Project * @date 2017/06/19 */ fun Class.getService(): T { - return ServiceManager.getService(this) + return ApplicationManager.getApplication().getService(this) } fun Class.getService(project: Project): T { - return ServiceManager.getService(project, this) + return project.getService(this) } \ No newline at end of file diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/util/PluginVersions.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/util/PluginVersions.kt index 993c04013..99b65ae06 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/util/PluginVersions.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/util/PluginVersions.kt @@ -17,6 +17,7 @@ package com.alibaba.smartfox.idea.common.util import com.intellij.ide.plugins.IdeaPluginDescriptor import com.intellij.ide.plugins.PluginManager +import com.intellij.ide.plugins.PluginManagerCore import com.intellij.ide.plugins.cl.PluginClassLoader import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.extensions.PluginId @@ -25,15 +26,15 @@ import com.intellij.openapi.extensions.PluginId * @author caikang */ object PluginVersions { - val baseVersion141 = 141 - val baseVersion143 = 143 - val baseVersion145 = 145 - val baseVersion162 = 162 - val baseVersion163 = 163 - val baseVersion171 = 171 + const val baseVersion141 = 141 + const val baseVersion143 = 143 + const val baseVersion145 = 145 + const val baseVersion162 = 162 + const val baseVersion163 = 163 + const val baseVersion171 = 171 val pluginId: PluginId = (javaClass.classLoader as PluginClassLoader).pluginId - val pluginDescriptor: IdeaPluginDescriptor = PluginManager.getPlugin(pluginId)!! + val pluginDescriptor: IdeaPluginDescriptor = PluginManagerCore.getPlugin(pluginId)!! /** * 获取当前安装的 plugin版本 diff --git a/idea-plugin/p3c-common/src/main/resources/messages/P3cBundle.xml b/idea-plugin/p3c-common/src/main/resources/messages/P3cBundle.xml index 438ba9469..1792436f3 100644 --- a/idea-plugin/p3c-common/src/main/resources/messages/P3cBundle.xml +++ b/idea-plugin/p3c-common/src/main/resources/messages/P3cBundle.xml @@ -4,8 +4,7 @@ 阿里编码规约 切换语言至英文(English) 切换语言至中文 - - 重启后生效]]> + 重启后生效]]> 编码规约扫描 关闭实时检测功能 打开实时检测功能 @@ -15,48 +14,28 @@ 修改为小写驼峰命名(lowerCamelCase) 为变量添加! 替换为 - 通过类 '%s' 直接访问静态成员 - '%s.%s' - + 通过类 '%s' 直接访问静态成员 '%s.%s' 添加 @Override 注解 为语句加上大括号 翻转 equals 调用 修改为 String[] str 模式 'l' 替换为 'L' - - #ref #loc]]> - - 避免通过一个类的对象引用访问此类的静态变量或静态方法,无谓增加编译器解析成本,直接用类名来访问即可。 - - 不应该通过类实例访问静态成员 - %s #loc - + #ref #loc]]> + 避免通过一个类的对象引用访问此类的静态变量或静态方法,无谓增加编译器解析成本,直接用类名来访问即可。 + 不应该通过类实例访问静态成员 %s #loc 不能使用过时的类或方法。 - - 所有的覆写方法,必须加@Override注解。 - - - #ref()缺少 '@Override' 注解 #loc]]> - - Map/Set的key为自定义对象时,必须重写hashCode和equals。 - - - 参数类型 %s 没有重写hashCode和equals #loc - - - #ref 是非线程安全的,请加锁或者使用局部变量 #loc]]> - - #ref 没有加大括号 #loc]]> - - #ref 应该作为方法 "%s()"的调用方,而不是参数 #loc]]> - - #ref 数组定义格式错误 #loc]]> - - #ref 应该以大写L结尾 #loc]]> - - #ref #loc]]> + 所有的覆写方法,必须加@Override注解。 + #ref()缺少 '@Override' 注解 #loc]]> + Map/Set的key为自定义对象时,必须重写hashCode和equals。 + 参数类型 %s 没有重写hashCode和equals #loc + #ref 是非线程安全的,请加锁或者使用局部变量 #loc]]> + #ref 没有加大括号 #loc]]> + #ref 应该作为方法 "%s()"的调用方,而不是参数 #loc]]> + #ref 数组定义格式错误 #loc]]> + #ref 应该以大写L结尾 #loc]]> + #ref #loc]]> @@ -81,8 +60,7 @@ ]]> - - Map/Set的key为自定义对象时,必须重写hashCode和equals。
diff --git a/idea-plugin/p3c-common/src/main/resources/messages/P3cBundle_en.xml b/idea-plugin/p3c-common/src/main/resources/messages/P3cBundle_en.xml index c6d7936f4..05b7ee145 100644 --- a/idea-plugin/p3c-common/src/main/resources/messages/P3cBundle_en.xml +++ b/idea-plugin/p3c-common/src/main/resources/messages/P3cBundle_en.xml @@ -4,68 +4,39 @@ Alibaba Coding Guidelines Switch language to English Switch language to Chinese - - restart to get effect.]]> + restart to get effect.]]> Alibaba Coding Guidelines Analyze - Close inspection on the fly - + Close inspection on the fly Open inspection on the fly Delete starting '$' or '_' Add/Extract @author - Refactor to upper case with underscore - + Refactor to upper case with underscore Refactor to lower camel case name Add '!' for variable Replace with - Access static '%s.%s' via - class '%s' reference. - - Add @Override - annotation - + Access static '%s.%s' via class '%s' reference. + Add @Override annotation Add braces to statement Flip 'equals()' - Replace with Java-style array - declaration - + Replace with Java-style array declaration Replace 'l' with 'L' - - #ref should replace with equals for wrapper type #loc]]> - A static field - or method should be directly referred by its class name instead of its corresponding object name. - - %s access static - member via class instance is prohibited #loc - + #ref should replace with equals for wrapper type #loc]]> + A static field or method should be directly referred by its class name instead of its corresponding object name. + %s access static member via class instance is prohibited #loc - Using a deprecated class or - method is prohibited. - - An overridden - method from an interface or abstract class must be marked with @Override annotation. - - - #ref() #loc]]> - - Custom class must override 'hashCode' and 'equals' while use as key for Map or value for Set. - - - Type of parameter %s does not override 'hashCode' and 'equals' #loc - - - #ref is unsafe,lock or use local variable #loc]]> - - #ref without braces #loc]]> - - #ref is argument of '%s()', instead of its target #loc]]> - - #ref ends with lowercase 'l' #loc]]> - - + Using a deprecated class or method is prohibited. + An overridden method from an interface or abstract class must be marked with @Override annotation. + #ref() #loc]]> + Custom class must override 'hashCode' and 'equals' while use as key for Map or value for Set. + Type of parameter %s does not override 'hashCode' and 'equals' #loc + #ref is unsafe,lock or use local variable #loc]]> + #ref without braces #loc]]> + #ref is argument of '%s()', instead of its target #loc]]> + #ref ends with lowercase 'l' #loc]]> + - - #ref #loc]]> + #ref #loc]]> @@ -90,8 +61,7 @@ Counter example: For getObject() and get0bject(), the first one has a letter 'O' ]]> - - Custom class must override 'hashCode' and 'equals' while use as key for Map or value for Set.
diff --git a/idea-plugin/p3c-common/src/main/resources/rulesets/java/ali-pmd.xml b/idea-plugin/p3c-common/src/main/resources/rulesets/java/ali-pmd.xml index 43b31b070..6516c043f 100644 --- a/idea-plugin/p3c-common/src/main/resources/rulesets/java/ali-pmd.xml +++ b/idea-plugin/p3c-common/src/main/resources/rulesets/java/ali-pmd.xml @@ -23,4 +23,5 @@ + diff --git a/idea-plugin/p3c-idea/build.gradle b/idea-plugin/p3c-idea/build.gradle index 992f534c7..6db292420 100644 --- a/idea-plugin/p3c-idea/build.gradle +++ b/idea-plugin/p3c-idea/build.gradle @@ -1,29 +1,27 @@ plugins { - id "org.jetbrains.intellij" version '0.4.5' + id 'java' + id "org.jetbrains.intellij" version "1.17.4" + + id "com.github.ben-manes.versions" version "0.53.0" } apply plugin: 'kotlin' apply plugin: 'idea' -def myPlugins = ['git4idea'] -def versionDotIndex = idea_version.indexOf('.') -def intVersion = versionDotIndex == -1 ? Integer.parseInt(idea_version) : Integer.parseInt(idea_version.substring(0, versionDotIndex)) -if (intVersion >= 2019 || (intVersion < 1000 && intVersion >= 193)) { - myPlugins = ['git4idea', 'java'] +def myPlugins = [] +if (shouldIncludeJava(idea_version)) { + myPlugins.add('java') } intellij { - version idea_version - plugins = myPlugins - pluginName plugin_name - updateSinceUntilBuild false - sandboxDirectory "idea-sandbox" + version.set(idea_version) + plugins.set(myPlugins) + pluginName.set(plugin_name) + updateSinceUntilBuild.set(false) } version plugin_version dependencies { - compile group: 'org.freemarker', name: 'freemarker', version: '2.3.25-incubating' - compile project(':p3c-common') - compile group: 'org.javassist', name: 'javassist', version: '3.21.0-GA' + implementation project(':p3c-common') } 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 old mode 100755 new mode 100644 index 0a19bf9f4..1ecdf2e69 --- a/idea-plugin/p3c-idea/src/main/resources/META-INF/plugin.xml +++ b/idea-plugin/p3c-idea/src/main/resources/META-INF/plugin.xml @@ -1,92 +1,246 @@ - com.alibaba.p3c.smartfox - Alibaba Java Coding Guidelines - Alibaba Java Coding Guidelines plugin support. + com.alibaba.p3c.xenoamess + Alibaba Java Coding Guidelines(XenoAmess TPM) + XenoAmess + Alibaba Java Coding Guidelines plugin support.(XenoAmess TPM)

+
+

Third-party maintenance by XenoAmess.

+
+

This Third-party maintenance(TPM) here is forked from original alibaba/p3c

+
+

Follows Apache license described in license

+
+

Sources can be found https://github.com/XenoAmess/p3c

+
+

Releases can be found at https://plugins.jetbrains.com/plugin/14109-alibaba-java-coding-guidelines-xenoamess-tpm-

+
+

This TPM aims to help maintain alibaba/p3c, fix bugs, and add improvements, as the original developer is too busy to handle them.

+
+

This TPM is NOT created, or maintained, or controlled by any alibaba employee, in other words it is not a TPM, not an official branch.

+
+

TPM maintainer XenoAmess have no knowledge with eclipse plugin development.

+
+

TPM maintainer XenoAmess suggest you only create pr for module idea-plugin and p3c-pmd, unless you really have a strong reason.

+
+ ]]>
- - - 2.1.0 -
  • Fix idea 2020.2 Ultimate compatibility issue
  • -
  • Minimum supported idea version up to 2018.3
  • -
  • Kotlin upgrade to 1.3.72
  • -
  • Disable real time inspect if file lines more than 3000 lines
  • -
  • Fix https://github.com/alibaba/p3c/issues/722
  • -
  • Fix https://github.com/alibaba/p3c/issues/620
  • + 2.2.4.0x-SNAPSHOT +
  • Fix 2024.1 compatibility issue
  • +
  • Fix 2024.2 compatibility issue
  • +
  • upgrade gradle & building jdk & intellij plugin version
  • -
      - 2.0.2 +
        2.2.2.0x +
      • Fix 2023.2 compatibility issue
      • +
      +
        2.2.1.0x +
      • Fix @Override missing error
      • +
      +
        2.2.0.0x +
      • Fix idea 2023.1 2023.2 2023.3 compatibility issue
      • +
      +
        2.1.1.6x-SNAPSHOT +
      • Fix idea 2023.1-EAP compatibility issue
      • +
      +
        2.1.1.5x +
      • Migrate deprecated/removal idea function usages
      • +
      +
        2.1.1.4x +
      • Fix idea 2022.1 Ultimate compatibility issue
      • +
      +
        2.1.1.3x +
      • pmd upgrade to 6.44.0
      • +
      • fix bugs of SneakyThrowsWithoutExceptionTypeRule
      • +
      • add com.alibaba.p3c.pmd.config>package_blacklist config. see https://github.com/XenoAmess/p3c/issues/211
      • +
      +
        2.1.1.2x +
      • pmd upgrade to 6.41.0
      • +
      • now allow use json for configuration too (p3c_config.json). see https://github.com/XenoAmess/p3c/issues/144
      • +
      • add addition rules mechanism
      • +
      • add an addition rule to detect using lombok.SneakyThrow annotation while not specify the type of exception to throw.
      • +
      • update deprecated pmd grammars in ServiceOrDaoClassShouldEndWithImplRule : @Image to @SimpleName
      • +
      • update deprecated pmd grammars in TestClassShouldEndWithTestNamingRule : to suite codes changes in AbstractJUnitRule
      • +
      +
        2.1.1.1x +
      • sync some minor fix in 2.1.1
      • +
      • pmd upgrade to 6.37.0
      • +
      • update deprecated grammars in PojoMustOverrideToStringRule
      • +
      • update deprecated pmd grammars in AvoidNewDateGetTimeRule : @ArgumentCount to @Size
      • +
      • update deprecated pmd grammars in BooleanPropertyShouldNotStartWithIsRule : @Image to @Name
      • +
      • update deprecated pmd grammars in BooleanPropertyShouldNotStartWithIsRule : @Image to @SimpleName
      • +
      • update missing attribute language="java" for some ruleset xml.
      • +
      • update deprecated pmd grammars in AvoidComplexConditionRule : @Ternary to null(@Ternary is always true in new versions of PMD)
      • +
      • update deprecated pmd grammars in StringConcatRule : @Image to @Operator
      • +
      • update deprecated pmd grammars in PojoMustOverrideToStringRule : MethodDeclarator[@ParameterCount] to @Arity
      • +
      • update deprecated pmd grammars in PojoMustOverrideToStringRule : MethodDeclarator[@Image] to @Name
      • +
      +
        2.1.1 +
      • Fix idea 2021.2 Ultimate compatibility issue
      • +
      +
        2.1.0.7x +
      • pmd upgrade to 6.36.0
      • +
      • upgrade other dependencies
      • +
      • fix https://github.com/alibaba/p3c/issues/832
      • +
      • fix https://github.com/XenoAmess/p3c/issues/118
      • +
      • fix https://github.com/alibaba/p3c/issues/757
      • +
      +
        2.1.0.6x +
      • pmd upgrade to 6.33.0
      • +
      • upgrade other dependencies
      • +
      +
        2.1.0.5x +
      • bugfix about LockShouldWithTryFinallyRule will throw NPE when node.type == null
      • +
      +
        2.1.0.4x +
      • pmd upgrade to 6.31.0
      • +
      • upgrade other dependencies
      • +
      +
        2.1.0.3x +
      • fix bugs about wrongly think new BigDecimal(Double.toString(0.0)) illegal. See: https://github.com/alibaba/p3c/issues/782
      • +
      +
        2.1.0.2x +
      • fix logics in rule LowerCamelCaseVariableNamingRule. Now we do not alarm in function with @Override
      • +
      • move package 'com.alibaba.p3c.pmd' to 'com.xenoamess.p3c.pmd'
      • +
      +
        2.1.0.1x +
      • pmd upgrade to 6.26.0
      • +
      • Kotlin upgrade to 1.4.0
      • +
      +
        2.1.0 +
      • Fix idea 2020.2 Ultimate compatibility issue
      • +
      • Minimum supported idea version up to 2018.3
      • +
      • Kotlin upgrade to 1.3.72
      • +
      • Disable real time inspect if file lines more than 3000 lines
      • +
      • Fix https://github.com/alibaba/p3c/issues/722
      • +
      • Fix https://github.com/alibaba/p3c/issues/620
      • +
      +
        2.0.2.6x +
      • fix code smells.
      • +
      • upgrade dependencies.
      • +
      +
        2.0.2.5x +
      • ignore AbstractMethodOrInterfaceMethodMustUseJavadocRule check for function who have @inheritdoc in javadoc.
      • +
      • fix some typos.
      • +
      • fix code smells.
      • +
      • upgrade dependencies.
      • +
      +
        2.0.2.4x +
      • add config mechanism to idea highlight.
      • +
      • upgrade x8l version.
      • +
      • fix code smells.
      • +
      +
        2.0.2.3x +
      • add config mechanism to both p3c-pmd and idea-plugin.
      • +
      • down priority EqualsHashCodeRule to 4.
      • +
      • EqualsHashCodeRule now only check non-Abstract class.
      • +
      +
        2.0.2.2x +
      • add SwitchExpressionRule to deal with switch expression, which is experimental in java 12 and 13, and finally public in java 14.Added a rule for checking SwitchExpression MUST have a default branch.
      • +
      • I'm new to pmd and XPATH thing, so if there be bug/false positive in the new added rule, please e-mail me or open issue on github.
      • +
      +
        2.0.2.1x +
      • learn from 2.0.2
      • +
      • update version of pmd from 6.18.0 to 6.22.0.
      • +
      • update version of kotlin from 1.3.71 to 1.3.72.
      • +
      • Bugfix about output some excess infos when analyze before commit. Thanks to geasskid@163.com 's bug report.
      • +
      +
        2.0.2
      • Fix idea 2020.1 Ultimate compatibility issue
        - 2.0.1 -
      • Fix idea 2019.3 compatibility issue
      • -
      • fix https://github.com/alibaba/p3c/issues/540
      • -
      • fix https://github.com/alibaba/p3c/issues/209
      • -
      • fix https://github.com/alibaba/p3c/issues/579
      • -
      • Add code style rule of lock
      • +
          2.0.1.4x +
        • add a Exception catch for some code to make sure will not corrupt when idea lib adds some more functions in future.
        • +
        • update version of pmd from 6.17.0 to 6.18.0.
        • +
        • code changes due to pmd upgrade.
        -
          - 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
        • +
            2.0.1.3x +
          • move groupID from com.alibaba.p3c to com.xenoamess.p3c, as I have no right to release an alibaba project in maven central.
          • +
          • bugfix for gitbook; add markdown guidelines.
          • +
          • remake pom for p3c-pmd.
          • +
          • reformat some kotlin codes
          • +
          • add travis-ci
          • +
          • add sonarcloud
          • +
          +
            2.0.1.2x +
          • reviews all pending prs before 2020/04/11 , and merged/improved some of them.
          • +
          • merged pr: special camel rule for MybatisGenerator's DOMapper classes.
          • +
          • merged pr: fix for check of BeanUtils' copyProperties, and add more tests for it.
          • +
          • merged pr: forbid Object Varargs, and change its priority from 1 to 4.
          • +
          • merged pr: forbid Object Varargs, and change its priority from 1 to 4.
          • +
          • upgrade some dependencies.
          • +
          • remake pom.xml in p3c-pmd.
          • +
          • fix some javadoc in p3c-pmd.
          • +
          • fix code smells.
          • +
          • fix some wrongly formatted xmls, including this plugin.xml.
          • +
          • add WARNING and WEAK_WARNING.
          • +
          +
            2.0.1.1x +
          • Fix idea 2020.1 compatibility issue
          • +
          • fix javadoc in p3c-cmd
          • +
          • fix clinic dependency in p3c-cmd
          • +
          • upgrade gradle wrapper
          • +
          • upgrade idea-plugin version
          • +
          • upgrade some dependencies
          • +
          +
            2.0.1 +
          • Fix idea 2019.3 compatibility issue
          • +
          • fix https://github.com/alibaba/p3c/issues/540
          • +
          • fix https://github.com/alibaba/p3c/issues/209
          • +
          • fix https://github.com/alibaba/p3c/issues/579
          • +
          • Add code style rule of lock
          • +
          +
            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.5 -
          • - Add rule [Recommended] The total number of lines for a method should not be more than 80. -
          • -
          • - Add rule [Recommended] Avoid using the negation operator '!'. -
          • -
          • - Add rule [Mandatory] When doing date formatting, "y" should be written in lowercase for "year" in a pattern statement -
          • -
          • https://github.com/alibaba/p3c/issues/264
          • -
          -
            - 1.0.4 -
          • fix https://github.com/alibaba/p3c/issues/217
          • -
          • fix https://github.com/alibaba/p3c/issues/208
          • -
          • fix https://github.com/alibaba/p3c/issues/195
          • -
          - - - - ]]> +
            1.0.5 +
          • Add rule [Recommended] The total number of lines for a method should not be more than 80.
          • +
          • Add rule [Recommended] Avoid using the negation operator '!'.
          • +
          • Add rule [Mandatory] When doing date formatting, "y" should be written in lowercase for "year" in a pattern statement
          • +
          • https://github.com/alibaba/p3c/issues/264
          • +
          +
            1.0.4 +
          • fix https://github.com/alibaba/p3c/issues/217
          • +
          • fix https://github.com/alibaba/p3c/issues/208
          • +
          • fix https://github.com/alibaba/p3c/issues/195
          • +
          + + + + ]]> - alibaba - 2.0.0 - - com.intellij.velocity - com.intellij.modules.java + + + + com.intellij.modules.java com.intellij.modules.platform com.intellij.modules.lang com.intellij.modules.vcs diff --git a/idea-plugin/p3c-idea/src/main/resources/META-INF/pluginIcon.svg b/idea-plugin/p3c-idea/src/main/resources/META-INF/pluginIcon.svg new file mode 100644 index 000000000..ef6c8c07e --- /dev/null +++ b/idea-plugin/p3c-idea/src/main/resources/META-INF/pluginIcon.svg @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/idea-plugin/p3c-idea/src/main/resources/META-INF/p3c.xml b/idea-plugin/p3c-idea/src/main/resources/META-INF/pluginWithJava.xml old mode 100755 new mode 100644 similarity index 76% rename from idea-plugin/p3c-idea/src/main/resources/META-INF/p3c.xml rename to idea-plugin/p3c-idea/src/main/resources/META-INF/pluginWithJava.xml index 9fbc30c5b..d662b769c --- a/idea-plugin/p3c-idea/src/main/resources/META-INF/p3c.xml +++ b/idea-plugin/p3c-idea/src/main/resources/META-INF/pluginWithJava.xml @@ -1,9 +1,4 @@ - - - com.alibaba.p3c.idea.component.CommonSettingsApplicationComponent - - com.alibaba.p3c.idea.component.AliProjectComponent @@ -43,10 +38,16 @@ interface="com.alibaba.p3c.idea.ep.InspectionActionExtensionPoint"/> - - - - + + + + + diff --git a/idea-plugin/settings.gradle b/idea-plugin/settings.gradle index f6db291f0..dc173e012 100644 --- a/idea-plugin/settings.gradle +++ b/idea-plugin/settings.gradle @@ -1,2 +1,11 @@ +plugins { + id "com.gradle.develocity" version "4.2.2" +} +develocity { + buildScan { + termsOfUseUrl = "https://gradle.com/terms-of-service" + termsOfUseAgree = "yes" + } +} include 'p3c-idea' -include 'p3c-common' +include 'p3c-common' \ No newline at end of file diff --git a/mvnw b/mvnw new file mode 100644 index 000000000..41c0f0c23 --- /dev/null +++ b/mvnw @@ -0,0 +1,310 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 000000000..86115719e --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/p3c-formatter/eclipse-codestyle.xml b/p3c-formatter/eclipse-codestyle.xml old mode 100755 new mode 100644 diff --git "a/p3c-gitbook/\347\211\210\346\234\254\345\216\206\345\217\262.md" "b/p3c-gitbook/\347\211\210\346\234\254\345\216\206\345\217\262.md" index 100142b7f..dc962a705 100644 --- "a/p3c-gitbook/\347\211\210\346\234\254\345\216\206\345\217\262.md" +++ "b/p3c-gitbook/\347\211\210\346\234\254\345\216\206\345\217\262.md" @@ -9,3 +9,4 @@ | 1.2.0 | 2017.5.20 | 1)根据云栖社区的“聚能聊”活动反馈,对手册的页码、排版、描述进行修正。2)增加final的适用场景描述。3)增加关于锁的粒度的说明。4)增加“指定集合大小”的详细说明以及正反例。5)增加卫语句的示例代码。6)明确数据库表示删除概念的字段名为is_deleted | | 1.3.0 | 2017.9.25 | 增加单元测试规约(PDF终极版),阿里开源的IDE代码规约检测插件:[点此下载](https://github.com/alibaba/p3c) 更多及时信息,请关注《阿里巴巴Java开发手册》官方公众号:![QRcode](images/QRcode.jpg)| | 1.3.1 | 2017.11.30 | 修正部分描述;采用和P3C开源IDE检测插件相同的Apache2.0协议。 | +| 1.3.1.1x | 2020.4.11 | 添加维护手册。修正部分markdown语法错误。 | \ No newline at end of file diff --git "a/p3c-gitbook/\347\273\264\346\212\244\346\211\213\345\206\214.md" "b/p3c-gitbook/\347\273\264\346\212\244\346\211\213\345\206\214.md" new file mode 100644 index 000000000..4b83c3017 --- /dev/null +++ "b/p3c-gitbook/\347\273\264\346\212\244\346\211\213\345\206\214.md" @@ -0,0 +1,39 @@ +# markdown维护手册0.2.0 +本手册并非你所阅读的markdown材料的一部分, +而是旨在更好地维护markdown材料而提出的, +对于markdown材料维护人员的要求规范。 + +## 0.及时更新该手册 +该手册发布地址为: +https://github.com/XenoAmess/markdown_documents_maintain_guide/tree/master + +在遇到了新的问题并解决后, +如果这个问题有可重复性, +并且是markdown相关问题, +请向markdown维护手册提出相应修改,并提pr。 + +相应的,请考虑定期从发布地址更新该手册。 + +## 1.标题的井号后面必须加至少一个空格 +例如,“## 维护手册”(例1.1)合法,而“##维护手册”(例1.2)不合法。 + +这个要求是因为,尽管idea等智能的markdown解析器完全能够解析例1.2, +但是市面上存在很多愚蠢但有很多人使用的解析器, +例如github的页面渲染。 + +所以,在此要求,所有人员提交修改前请用“^\s*#+[^#\s]”对全书每一行进行正则扫描 +(在idea中自带正则扫描功能,推荐使用idea作为markdown编辑工具) + +并对于每一个发现的问题予以及时订正。 + +## 2.不要出现四级标题以下的标题(五级或者更多) +例如,“## 维护手册”(例2.1)合法,而“###### 维护手册”(例2.2)不合法。 + +这个要求是因为,尽管idea等智能的markdown解析器完全能够解析例2.2, +但是市面上存在很多愚蠢但有很多人使用的解析器, +例如github的页面渲染。 + +所以,在此要求,所有人员提交修改前请用“^\s*#####+”对全书每一行进行正则扫描 +(在idea中自带正则扫描功能,推荐使用idea作为markdown编辑工具) + +并对于每一个发现的问题予以及时订正。 diff --git "a/p3c-gitbook/\347\274\226\347\250\213\350\247\204\347\272\246/\345\221\275\345\220\215\351\243\216\346\240\274.md" "b/p3c-gitbook/\347\274\226\347\250\213\350\247\204\347\272\246/\345\221\275\345\220\215\351\243\216\346\240\274.md" index 2beabc428..c5a3d04e2 100644 --- "a/p3c-gitbook/\347\274\226\347\250\213\350\247\204\347\272\246/\345\221\275\345\220\215\351\243\216\346\240\274.md" +++ "b/p3c-gitbook/\347\274\226\347\250\213\350\247\204\347\272\246/\345\221\275\345\220\215\351\243\216\346\240\274.md" @@ -1,5 +1,5 @@ # 一、编程规约 -##(一)命名风格 +## (一)命名风格 1. 【强制】代码中的命名均不能以下划线或美元符号开始,也不能以下划线或美元符号结束。
          反例:`_name / __name / $name / name_ / name$ / name__` diff --git a/p3c-pmd/.gitignore b/p3c-pmd/.gitignore index f9481d30d..72280c8ff 100644 --- a/p3c-pmd/.gitignore +++ b/p3c-pmd/.gitignore @@ -80,7 +80,6 @@ config.client.* temp/ *.pid -*.orig hsf.configuration/ diff --git a/p3c-pmd/.mvn/wrapper/MavenWrapperDownloader.java b/p3c-pmd/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 000000000..b901097f2 --- /dev/null +++ b/p3c-pmd/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,117 @@ +/* + * Copyright 2007-present the original author or authors. + * + * 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. + */ +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.6"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if(mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if(mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if(!outputFile.getParentFile().exists()) { + if(!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/p3c-pmd/.mvn/wrapper/maven-wrapper.jar b/p3c-pmd/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 000000000..2cc7d4a55 Binary files /dev/null and b/p3c-pmd/.mvn/wrapper/maven-wrapper.jar differ diff --git a/p3c-pmd/.mvn/wrapper/maven-wrapper.properties b/p3c-pmd/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 000000000..642d572ce --- /dev/null +++ b/p3c-pmd/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/p3c-pmd/README.md b/p3c-pmd/README.md index 97b00068d..13eeb399a 100644 --- a/p3c-pmd/README.md +++ b/p3c-pmd/README.md @@ -9,9 +9,9 @@ ### Maven ```xml - com.alibaba.p3c + com.xenoamess.p3c p3c-pmd - 1.3.6 + 2.2.4.0x-SNAPSHOT ``` ### Gradle @@ -243,7 +243,7 @@ Note: In IDE, Javadoc can be seen directly when hovering, which is a good way to ### Other -* 1``[Mandatory]`` Avoid using *Apache Beanutils* to copy attributes. +* 1``[Mandatory]`` Avoid using *Apache BeanUtils* to copy attributes. * 2 ``[Mandatory]`` When using regex, precompile needs to be done in order to increase the matching performance and preferably stored as a constant. Note: Do not define Pattern pattern = Pattern.compile(.); within method body. * 3 ``[Mandatory]`` Variables must add exclamatory mark when passing to velocity engine from backend, like $!{var}. diff --git a/p3c-pmd/mvnw b/p3c-pmd/mvnw new file mode 100644 index 000000000..41c0f0c23 --- /dev/null +++ b/p3c-pmd/mvnw @@ -0,0 +1,310 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/p3c-pmd/mvnw.cmd b/p3c-pmd/mvnw.cmd new file mode 100644 index 000000000..86115719e --- /dev/null +++ b/p3c-pmd/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/p3c-pmd/pom.xml b/p3c-pmd/pom.xml index c465b924e..b36e1e746 100644 --- a/p3c-pmd/pom.xml +++ b/p3c-pmd/pom.xml @@ -1,272 +1,902 @@ - - 4.0.0 - - org.sonatype.oss - oss-parent - 9 - - com.alibaba.p3c - p3c-pmd - 2.1.1 - jar - p3c-pmd - - UTF-8 - 6.15.0 - 1.8 - 1.3.2 - 1.3.72 - - Alibaba Java Coding Guidelines PMD implementations - https://github.com/alibaba/p3c - 2017 + + 4.0.0 + com.xenoamess.p3c + p3c-pmd + 2.2.4.0x-SNAPSHOT + jar + p3c-pmd + + UTF-8 + ${maven.compiler.encoding} + + ${maven.compiler.encoding} + - - - Apache 2 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - A business-friendly OSS license - - + 8 + ${java.version} + ${java.version} + + + + 6.55.0 + 1.3.2 + 2.2.21 + 2.3.9 + 3.20.0 + 2.21.0 + 4.13.2 + 2.20.1 + + + + 2.20.1 + 3.3.1 + 3.2.8 + 3.21.2 + 3.14.1 + 3.2.0 + 3.12.0 + 3.4.1 + 3.0.0-M1 + 3.20.0 + 3.9.0 + 3.1.4 + 3.5.4 + 1.24 + 0.8.14 + 2.25.2 + 1.7.36 + + true + 3.6.2 + 3.5.0 + 11.1.0 + src/site/resources/checkstyle + + + Alibaba Java Coding Guidelines PMD implementations(XenoAmess + TPM) + + https://github.com/xenoamess/p3c + 2017 - - https://github.com/alibaba/p3c - scm:git:https://git@github.com/alibaba/p3c.git - + + + Apache 2 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + A business-friendly OSS license + + - - Alibaba Group - https://github.com/alibaba - + + https://github.com/xenoamess/p3c + scm:git:https://git@github.com/xenoamess/p3c.git + + - - - XuanTan - https://github.com/xuantan - zhangym124@gmail.com - - - ChangLe - https://github.com/LQZYC - lqleo323@gmail.com - - - ZengHou - https://github.com/fw8899 - fengwei1983@gmail.com - - - ShengYan - http://smiler158.github.io/ - smiler158@163.com - - - KeQi - lyzw2009@gmail.com - - - JunLie - 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 - - - javax.annotation - javax.annotation-api - ${annotation.version} - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - ${kotlin.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 - - - + + Alibaba Group + https://github.com/alibaba + + + + + XuanTan + https://github.com/xuantan + zhangym124@gmail.com + + + ChangLe + https://github.com/LQZYC + lqleo323@gmail.com + + + ZengHou + https://github.com/fw8899 + fengwei1983@gmail.com + + + ShengYan + http://smiler158.github.io/ + smiler158@163.com + + + KeQi + lyzw2009@gmail.com + + + JunLie + https://github.com/SeanCai + sean.caikang@gmail.com + + + MoYan + https://github.com/imu2008 + panhuawenmail@gmail.com + + + XenoAmess + xenoamess@gmail.com + XenoAmess + https://github.com/xenoamess + + + + + + net.sourceforge.pmd + pmd-java + ${pmd.version} + + + net.sourceforge.pmd + pmd-vm + ${pmd.version} + + + net.sourceforge.pmd + pmd-test + ${pmd.version} + test + + + javax.annotation + javax.annotation-api + ${annotation.version} + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + + com.xenoamess + x8l + ${x8l.version} + + + + - - com.alibaba.p3c - p3c-pmd - 2.0.1 - + + commons-io + commons-io + ${commons-io.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + commons-collections + commons-collections + 3.2.2 + + + org.apache.commons + commons-text + 1.14.0 + + + com.squareup.okio + okio + 3.0.0 + + + com.beust + jcommander + 1.82 + + + junit + junit + ${junit.version} + + + com.fasterxml.jackson + jackson-bom + ${jackson.version} + pom + import + + + org.apache.logging.log4j + log4j-api + ${log4j.version} + + + org.apache.logging.log4j + log4j-core + ${log4j.version} + + + org.apache.logging.log4j + log4j-bom + ${log4j.version} + pom + + + org.slf4j + slf4j-log4j12 + ${slf4j.version} + + + org.slf4j + slf4j-api + ${slf4j.version} + + + org.slf4j + jcl-over-slf4j + ${slf4j.version} + - - - kotlin-maven-plugin - org.jetbrains.kotlin - ${kotlin.version} - - - compile - - compile - - - - ${project.basedir}/src/main/kotlin - ${project.basedir}/src/main/java - - - - - test-compile - - test-compile - - - - ${project.basedir}/src/test/kotlin - ${project.basedir}/src/test/java - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.0 - - ${maven.compiler.target} - ${maven.compiler.target} - UTF-8 - - - - - default-compile - none - - - - default-testCompile - none - - - java-compile - compile - - compile - - - - java-test-compile - test-compile - - testCompile - - - - - - maven-assembly-plugin - 3.0.0 - - - jar-with-dependencies - - - - - make-assembly - package - - single - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.10.4 - - - attach-javadocs - - jar - - - - - - - date - - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.6 - - - sign-artifacts - verify - - sign - - - - - - - + + + + + maven.compiler.release + + [9,) + + + ${java.version} + + + + update_dependencies + + + + + org.codehaus.mojo + versions-maven-plugin + ${versions-maven-plugin.version} + + false + + org.slf4j:* + net.sourceforge.pmd:* + + + + + initialize + + update-properties + + + + + + + + + sonatype-oss-release + + + + org.apache.maven.plugins + maven-gpg-plugin + ${maven-gpg-plugin.version} + + + sign-artifacts + verify + + sign + + + + + + + + + develop + + + + org.apache.maven.plugins + maven-pmd-plugin + ${maven-pmd-plugin.version} + + false + ${project.build.sourceEncoding} + + ${maven.compiler.target} + true + 3 + + rulesets/java/imports.xml + 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 + rulesets/java/xenoamess-additional.xml + + + **/FixClassTypeResolver.java + + + + + pmd1 + initialize + + check + + + + + + net.sourceforge.pmd + pmd-core + ${pmd.version} + + + net.sourceforge.pmd + pmd-java + ${pmd.version} + + + net.sourceforge.pmd + pmd-vm + ${pmd.version} + + + ${project.groupId} + ${project.artifactId} + [1,${project.version}] + + + + + com.xenoamess + remove-unused-imports-maven-plugin + + 0.0.6 + + + rui1 + initialize + + process + + + + UnusedImports + DuplicateImports + UnnecessaryReturn + + ${basedir}/target/pmd.xml + + false + + + + + + + + + + enforce + + + enforce.activate + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + + enforce + + + + + + + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + ${checkstyle.plugin.version} + + + validate + + check + + + + + + ${checkstyle.configdir}/checkstyle.xml + + true + + false + + + + com.puppycrawl.tools + checkstyle + ${checkstyle.version} + + + + + + + + + + + + io.takari + maven + 0.7.7 + + + + wrapper + + generate-resources + + + + + org.apache.maven.plugins + maven-site-plugin + ${maven-site-plugin.version} + + + + org.apache.maven.plugins + maven-project-info-reports-plugin + ${maven-project-info-reports-plugin.version} + + + org.apache.maven.plugins + maven-javadoc-plugin + ${maven-javadoc-plugin.version} + + en + private + ../javadocs + ${project.build.sourceEncoding} + ${project.reporting.outputEncoding} + + -J-Duser.language=en_US + + + + + date + + + apiNote + a + API Note: + + + implSpec + a + Implementation Requirements: + + + implNote + a + Implementation Note: + + + param + + + return + + + throws + + + since + + + version + + + serialData + + + see + + + + ${maven.compiler.source} + + + + + + + + package + + jar + + + + + + org.apache.maven.plugins + maven-deploy-plugin + ${maven-deploy-plugin.version} + + + org.apache.maven.plugins + maven-source-plugin + ${maven-source-plugin.version} + + + package + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.encoding} + ${maven.compiler.source} + ${maven.compiler.target} + + + + + default-compile + none + + + + default-testCompile + none + + + java-compile + compile + + compile + + + + java-test-compile + test-compile + + testCompile + + + + + + + + org.apache.maven.plugins + maven-pmd-plugin + ${maven-pmd-plugin.version} + + ${project.build.sourceEncoding} + + ${maven.compiler.target} + true + 3 + + rulesets/java/imports.xml + 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 + rulesets/java/xenoamess-additional.xml + + + **/FixClassTypeResolver.java + + + + + pmd2 + verify + + check + + + + + + net.sourceforge.pmd + pmd-core + ${pmd.version} + + + net.sourceforge.pmd + pmd-java + ${pmd.version} + + + net.sourceforge.pmd + pmd-vm + ${pmd.version} + + + ${project.groupId} + ${project.artifactId} + [1,${project.version}] + + + + + kotlin-maven-plugin + org.jetbrains.kotlin + ${kotlin.version} + + + compile + + compile + + + + ${project.basedir}/src/main/kotlin + + ${project.basedir}/src/main/java + + + + + + test-compile + + test-compile + + + + ${project.basedir}/src/test/kotlin + + ${project.basedir}/src/test/java + + + + + + + + org.jacoco + jacoco-maven-plugin + ${jacoco-maven-plugin.version} + + + prepare-agent + validate + + prepare-agent + + + + report + prepare-package + + report + + + + + + ${project.basedir}/src/main/java + ${project.basedir}/src/test/java + + + + + + + + + + + + + + + + + + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + enforce-maven + + enforce + + + + + (,2.1.0),(2.1.0,2.2.0),(2.2.0,) + + Maven 2.1.0 and 2.2.0 produce + incorrect GPG signatures and checksums + respectively. + + + + + + + + + org.codehaus.mojo + animal-sniffer-maven-plugin + ${animal-sniffer-maven-plugin.version} + + + test + + check + + + + + + org.codehaus.mojo.signature + java18 + 1.0 + + + + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + ${maven-javadoc-plugin.version} + + en + private + ../javadocs + ${project.build.sourceEncoding} + ${project.reporting.outputEncoding} + + -J-Duser.language=en_US + + + + + date + + + apiNote + a + API Note: + + + implSpec + a + Implementation Requirements: + + + implNote + a + Implementation Note: + + + param + + + return + + + throws + + + since + + + version + + + serialData + + + see + + + + ${maven.compiler.source} + + + + + + + org.jacoco + jacoco-maven-plugin + + + + + report + + + + + + + + + + central + https://repo1.maven.org/maven2/ + + + + + + + sonatype-nexus-snapshots + Sonatype Nexus Snapshots + https://oss.sonatype.org/content/repositories/snapshots/ + + + sonatype-nexus-staging + Nexus Release Repository + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + + + \ No newline at end of file diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/AbstractXpathRule.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/AbstractXpathRule.java deleted file mode 100644 index 8aede7229..000000000 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/AbstractXpathRule.java +++ /dev/null @@ -1,48 +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.pmd.lang; - -import com.alibaba.p3c.pmd.I18nResources; - -import net.sourceforge.pmd.lang.ast.Node; -import net.sourceforge.pmd.lang.rule.XPathRule; - -/** - * @author caikang - * @date 2017/05/25 - */ -public abstract class AbstractXpathRule extends XPathRule { - @Override - public void setDescription(String description) { - super.setDescription(I18nResources.getMessageWithExceptionHandled(description)); - } - - @Override - public void setMessage(String message) { - super.setMessage(I18nResources.getMessageWithExceptionHandled(message)); - } - - @Override - public void addViolationWithMessage(Object data, Node node, String message) { - super.addViolationWithMessage(data, node, I18nResources.getMessageWithExceptionHandled(message)); - } - - @Override - public void addViolationWithMessage(Object data, Node node, String message, Object[] args) { - super.addViolationWithMessage(data, node, - String.format(I18nResources.getMessageWithExceptionHandled(message), args)); - } -} diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/namelist/NameListConfig.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/namelist/NameListConfig.java deleted file mode 100644 index ba454fbab..000000000 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/namelist/NameListConfig.java +++ /dev/null @@ -1,34 +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.pmd.lang.java.util.namelist; - -import com.alibaba.p3c.pmd.lang.java.util.SpiLoader; - -/** - * @author changle.lq - * @date 2017/03/27 - */ -public class NameListConfig { - public static final NameListService NAME_LIST_SERVICE = getNameListService(); - - private static NameListService getNameListService() { - NameListService instance = SpiLoader.getInstance(NameListService.class); - if (instance == null) { - instance = new NameListServiceImpl(); - } - return instance; - } -} diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/namelist/NameListService.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/namelist/NameListService.java deleted file mode 100644 index 381e3a4d4..000000000 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/namelist/NameListService.java +++ /dev/null @@ -1,45 +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.pmd.lang.java.util.namelist; - -import java.util.List; -import java.util.Map; - -/** - * @author changle.lq - * @date 2017/03/23 - */ -public interface NameListService { - /** - * get name list - * @param className class name - * @param name type name - * @return name list - */ - List getNameList(String className,String name); - - /** - * get config - * @param className class name - * @param name type name - * @param kClass type of key - * @param vClass type of value - * @param type of key - * @param type of value - * @return name list - */ - Map getNameMap(String className,String name,Class kClass,Class vClass); -} diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/namelist/NameListServiceImpl.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/namelist/NameListServiceImpl.java deleted file mode 100644 index 186458aee..000000000 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/namelist/NameListServiceImpl.java +++ /dev/null @@ -1,76 +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.pmd.lang.java.util.namelist; - -import java.io.IOException; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -/** - * @author changle.lq - * @date 2017/03/27 - */ -public class NameListServiceImpl implements NameListService { - - private static final String NAME_LIST_PROPERTY_FILE_NAME = "namelist.properties"; - private static final Properties PROPERTIES = initProperties(); - private static final String SEPARATOR = "_"; - - private static Properties initProperties() { - LinkedProperties props = new LinkedProperties(); - ClassLoader classLoader = NameListServiceImpl.class.getClassLoader(); - try { - props.load(classLoader.getResourceAsStream(NAME_LIST_PROPERTY_FILE_NAME)); - } catch (IOException ex) { - throw new IllegalStateException("Load namelist.properties fail", ex); - } - return props; - } - - @Override - public List getNameList(String className, String name) { - Gson gson = new Gson(); - return gson.fromJson((String)PROPERTIES.get(className + SEPARATOR + name), - new TypeToken>() {}.getType()); - } - - @Override - public Map getNameMap(String className, String name, Class kClass, Class vClass) { - Gson gson = new Gson(); - return gson.fromJson((String)PROPERTIES.get(className + SEPARATOR + name), - new TypeToken>() { - }.getType()); - } - - private static class LinkedProperties extends Properties { - private LinkedHashSet linkedKeys = new LinkedHashSet<>(); - - @Override - public Object put(Object key, Object value) { - linkedKeys.add(key); - return super.put(key, value); - } - - public int getSize() { - return linkedKeys.size(); - } - } -} diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/I18nResources.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/I18nResources.java similarity index 84% rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/I18nResources.java rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/I18nResources.java index c6c4973f4..d1afb21c1 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/I18nResources.java +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/I18nResources.java @@ -13,7 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.p3c.pmd; +package com.xenoamess.p3c.pmd; + +import org.jetbrains.annotations.NotNull; import java.io.BufferedInputStream; import java.io.IOException; @@ -37,11 +39,11 @@ public class I18nResources { private static final String XML_LITERAL = "xml"; - private static String lang = System.getProperty("pmd.language", "zh"); + private static final String LANG = System.getProperty("pmd.language", "zh"); private static Locale currentLocale; - private static ResourceBundle resourceBundle = changeLanguage(lang); + private static ResourceBundle resourceBundle = changeLanguage(LANG); public static ResourceBundle changeLanguage(String language) { Locale locale = Locale.CHINESE.getLanguage().equals(language) ? Locale.CHINESE : Locale.ENGLISH; @@ -90,7 +92,7 @@ public static String getMessageWithExceptionHandled(String key) { } public static class XmlResourceBundle extends ResourceBundle { - private Properties props; + private final Properties props; XmlResourceBundle(InputStream stream) throws IOException { props = new Properties(); @@ -98,16 +100,22 @@ public static class XmlResourceBundle extends ResourceBundle { } @Override - protected Object handleGetObject(String key) { - return props.getProperty(key); + @NotNull + protected Object handleGetObject(@NotNull String key) { + Object value = props.getProperty(key); + if (value == null) { + return key; + } + return value; } @Override + @NotNull public Enumeration getKeys() { List keys = new ArrayList<>(); Enumeration enumeration = props.keys(); while (enumeration.hasMoreElements()) { - keys.add((String)enumeration.nextElement()); + keys.add((String) enumeration.nextElement()); } return Collections.enumeration(keys); } @@ -129,15 +137,15 @@ public Locale getFallbackLocale(String baseName, Locale locale) { @Override public ResourceBundle newBundle(String baseName, - Locale locale, - String format, - ClassLoader loader, - boolean reload) - throws IllegalAccessException, - InstantiationException, - IOException { + Locale locale, + String format, + ClassLoader loader, + boolean reload) + throws IllegalAccessException, + InstantiationException, + IOException { if (baseName == null || locale == null - || format == null || loader == null) { + || format == null || loader == null) { throw new NullPointerException(); } ResourceBundle bundle = null; @@ -160,7 +168,7 @@ public ResourceBundle newBundle(String baseName, } private InputStream getInputStream(ClassLoader loader, String resourceName) - throws IOException { + throws IOException { URL url = loader.getResource(resourceName); if (url == null) { return null; diff --git a/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/config/P3cConfigDataBean.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/config/P3cConfigDataBean.java new file mode 100644 index 000000000..8971f536d --- /dev/null +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/config/P3cConfigDataBean.java @@ -0,0 +1,166 @@ +package com.xenoamess.p3c.pmd.config; + +import com.xenoamess.x8l.ContentNode; +import com.xenoamess.x8l.X8lTree; +import com.xenoamess.x8l.databind.X8lDataBean; +import com.xenoamess.x8l.databind.X8lDataBeanFieldMark; +import com.xenoamess.x8l.dealers.LanguageDealer; +import org.jetbrains.annotations.NotNull; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.logging.Logger; + +import static com.xenoamess.x8l.databind.X8lDataBeanDefaultParser.getLastFromList; +import static java.util.logging.Level.WARNING; + +/** + * @author XenoAmess + * @date 2020/04/24 + */ +public class P3cConfigDataBean implements X8lDataBean { + + @SuppressWarnings("unused") + public static @NotNull + Set getContentNodeAsStringSet(@NotNull List list) { + Object lastObject = getLastFromList(list); + if (!(lastObject instanceof ContentNode)) { + return new HashSet<>(0); + } + Set res = ((ContentNode) lastObject).asStringSetTrimmed(); + if (res != null) { + res.remove(""); + } + return res; + } + + @SuppressWarnings("unused") + public static @NotNull + HashMap> getRuleClassPairBlackListMap(@NotNull List list) { + ContentNode node = ((ContentNode) getLastFromList(list)); + if (node == null) { + return new HashMap<>(0); + } + List contentNodeChildren = node.getContentNodesFromChildren(); + if (contentNodeChildren.size() == 0) { + return new HashMap<>(0); + } + HashMap> res = new HashMap<>(contentNodeChildren.size()); + + for (ContentNode au : contentNodeChildren) { + res.put( + au.getName().trim(), + au.asStringSetTrimmed() + ); + } + return res; + } + + private static final Logger LOGGER = Logger.getLogger(P3cConfigDataBean.class.getName()); + + private X8lTree p3cConfigX8lTree; + + @X8lDataBeanFieldMark( + paths = { + "com.alibaba.p3c.pmd.config>rule_blacklist" + }, + parser = P3cConfigDataBean.class, + functionName = "getContentNodeAsStringSet" + ) + private Set ruleBlackListSet; + + @X8lDataBeanFieldMark( + paths = { + "com.alibaba.p3c.pmd.config>class_blacklist" + }, + parser = P3cConfigDataBean.class, + functionName = "getContentNodeAsStringSet" + ) + private Set classBlackListSet; + + @X8lDataBeanFieldMark( + paths = { + "com.alibaba.p3c.pmd.config>package_blacklist" + }, + parser = P3cConfigDataBean.class, + functionName = "getContentNodeAsStringSet" + ) + private Set packageBlackListSet; + + @X8lDataBeanFieldMark( + paths = { + "com.alibaba.p3c.pmd.config>rule_class_pair_blacklist" + }, + parser = P3cConfigDataBean.class, + functionName = "getRuleClassPairBlackListMap" + ) + private Map> ruleClassPairBlackListMap; + + public void tryPatchP3cConfigDataBean( + @NotNull File file, + @NotNull LanguageDealer languageDealer + ) { + if (file.exists() && file.isFile()) { + try { + X8lTree patchConfigX8lTree = X8lTree.load( + file, languageDealer + ); + this.getP3cConfigX8lTree().append(patchConfigX8lTree); + this.loadFromX8lTree(this.getP3cConfigX8lTree()); + } catch (IOException e) { + LOGGER.log(WARNING, "reading config file" + file + " fails, IO fails.", e); + } catch (Exception e) { + LOGGER.log(WARNING, "reading config file" + file + "fails, grammar wrong.", e); + } + } + } + + //-----getters and setters + + + public X8lTree getP3cConfigX8lTree() { + return p3cConfigX8lTree; + } + + public void setP3cConfigX8lTree(X8lTree p3cConfigX8lTree) { + this.p3cConfigX8lTree = p3cConfigX8lTree; + } + + public Set getRuleBlackListSet() { + return ruleBlackListSet; + } + + public void setRuleBlackListSet(Set ruleBlackListSet) { + this.ruleBlackListSet = ruleBlackListSet; + } + + public Set getClassBlackListSet() { + return classBlackListSet; + } + + public void setClassBlackListSet(Set classBlackListSet) { + this.classBlackListSet = classBlackListSet; + } + + public Map> getRuleClassPairBlackListMap() { + return ruleClassPairBlackListMap; + } + + public void setRuleClassPairBlackListMap(Map> ruleClassPairBlackListMap) { + this.ruleClassPairBlackListMap = ruleClassPairBlackListMap; + } + + public Set getPackageBlackListSet() { + return packageBlackListSet; + } + + public void setPackageBlackListSet(Set packageBlackListSet) { + this.packageBlackListSet = packageBlackListSet; + } + +} diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/fix/FixClassTypeResolver.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/fix/FixClassTypeResolver.java similarity index 94% rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/fix/FixClassTypeResolver.java rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/fix/FixClassTypeResolver.java index 0a58fe699..99e548020 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/fix/FixClassTypeResolver.java +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/fix/FixClassTypeResolver.java @@ -1,21 +1,10 @@ -/** +/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ -package com.alibaba.p3c.pmd.fix; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.annotation.Generated; - -import com.alibaba.p3c.pmd.lang.java.util.NumberConstants; -import com.alibaba.p3c.pmd.lang.java.util.StringAndCharConstants; +package com.xenoamess.p3c.pmd.fix; +import com.xenoamess.p3c.pmd.lang.java.util.NumberConstants; +import com.xenoamess.p3c.pmd.lang.java.util.StringAndCharConstants; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.ASTAdditiveExpression; import net.sourceforge.pmd.lang.java.ast.ASTAllocationExpression; @@ -67,6 +56,15 @@ import net.sourceforge.pmd.lang.java.typeresolution.ClassTypeResolver; import net.sourceforge.pmd.lang.java.typeresolution.PMDASMClassLoader; +import javax.annotation.Generated; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + // // Helpful reading: // http://www.janeg.ca/scjp/oper/promotions.html @@ -183,7 +181,7 @@ public Object visit(ASTCompilationUnit node, Object data) { @Override public Object visit(ASTImportDeclaration node, Object data) { - ASTName importedType = (ASTName)node.jjtGetChild(0); + ASTName importedType = (ASTName) node.jjtGetChild(0); if (importedType.getType() != null) { node.setType(importedType.getType()); } else { @@ -242,7 +240,7 @@ public Object visit(ASTName node, Object data) { // 1) Parent is a PackageDeclaration, which is not a type // 2) Parent is a ImportDeclaration, this is handled elsewhere. if (!(node.jjtGetParent() instanceof ASTPackageDeclaration - || node.jjtGetParent() instanceof ASTImportDeclaration)) { + || node.jjtGetParent() instanceof ASTImportDeclaration)) { String name = node.getImage(); if (name.indexOf(StringAndCharConstants.DOT) != -1) { name = name.substring(0, name.indexOf(StringAndCharConstants.DOT)); @@ -252,7 +250,7 @@ public Object visit(ASTName node, Object data) { } else { // Carry over the type from the declaration if (node.getNameDeclaration().getNode() instanceof TypeNode) { - node.setType(((TypeNode)node.getNameDeclaration().getNode()).getType()); + node.setType(((TypeNode) node.getNameDeclaration().getNode()).getType()); } } return super.visit(node, data); @@ -515,9 +513,9 @@ public Object visit(ASTLiteral node, Object data) { public Object visit(ASTAllocationExpression node, Object data) { super.visit(node, data); boolean notRollupTypeUnary = node.jjtGetNumChildren() >= NumberConstants.INTEGER_SIZE_OR_LENGTH_2 - && node.jjtGetChild(1) instanceof ASTArrayDimsAndInits - || node.jjtGetNumChildren() >= NumberConstants.INTEGER_SIZE_OR_LENGTH_3 - && node.jjtGetChild(NumberConstants.INDEX_2) instanceof ASTArrayDimsAndInits; + && node.jjtGetChild(1) instanceof ASTArrayDimsAndInits + || node.jjtGetNumChildren() >= NumberConstants.INTEGER_SIZE_OR_LENGTH_3 + && node.jjtGetChild(NumberConstants.INDEX_2) instanceof ASTArrayDimsAndInits; if (!notRollupTypeUnary) { rollupTypeUnary(node); } @@ -562,7 +560,7 @@ private void rollupTypeUnary(TypeNode typeNode) { if (node.jjtGetNumChildren() >= 1) { Node child = node.jjtGetChild(0); if (child instanceof TypeNode) { - typeNode.setType(((TypeNode)child).getType()); + typeNode.setType(((TypeNode) child).getType()); } } } @@ -578,13 +576,13 @@ private void rollupTypeUnaryNumericPromotion(TypeNode typeNode) { if (node.jjtGetNumChildren() >= 1) { Node child = node.jjtGetChild(0); if (child instanceof TypeNode) { - Class type = ((TypeNode)child).getType(); + Class type = ((TypeNode) child).getType(); if (type != null) { if (byte.class.getName().equals(type.getName()) || short.class.getName().equals(type.getName()) - || char.class.getName().equals(type.getName())) { + || char.class.getName().equals(type.getName())) { populateType(typeNode, int.class.getName()); } else { - typeNode.setType(((TypeNode)child).getType()); + typeNode.setType(((TypeNode) child).getType()); } } } @@ -603,25 +601,25 @@ private void rollupTypeBinaryNumericPromotion(TypeNode typeNode) { Node child1 = node.jjtGetChild(0); Node child2 = node.jjtGetChild(1); if (child1 instanceof TypeNode && child2 instanceof TypeNode) { - Class type1 = ((TypeNode)child1).getType(); - Class type2 = ((TypeNode)child2).getType(); + Class type1 = ((TypeNode) child1).getType(); + Class type2 = ((TypeNode) child2).getType(); if (type1 != null && type2 != null) { // Yeah, String is not numeric, but easiest place to handle // it, only affects ASTAdditiveExpression if (String.class.getName().equals(type1.getName()) || String.class.getName().equals( - type2.getName())) { + type2.getName())) { populateType(typeNode, String.class.getName()); } else if (boolean.class.getName().equals(type1.getName()) || boolean.class.getName().equals( - type2.getName())) { + type2.getName())) { populateType(typeNode, boolean.class.getName()); } else if (double.class.getName().equals(type1.getName()) || double.class.getName().equals( - type2.getName())) { + type2.getName())) { populateType(typeNode, double.class.getName()); } else if (float.class.getName().equals(type1.getName()) || float.class.getName().equals( - type2.getName())) { + type2.getName())) { populateType(typeNode, float.class.getName()); } else if (long.class.getName().equals(type1.getName()) || long.class.getName().equals( - type2.getName())) { + type2.getName())) { populateType(typeNode, long.class.getName()); } else { populateType(typeNode, int.class.getName()); @@ -632,7 +630,7 @@ private void rollupTypeBinaryNumericPromotion(TypeNode typeNode) { // Yeah, String is not numeric, but easiest place to handle // it, only affects ASTAdditiveExpression boolean populateString = type1 != null && String.class.getName().equals(type1.getName()) - || type2 != null && String.class.getName().equals(type2.getName()); + || type2 != null && String.class.getName().equals(type2.getName()); if (populateString) { populateType(typeNode, String.class.getName()); } @@ -671,8 +669,8 @@ private void populateType(TypeNode node, String className) { if (myType == null && qualifiedName != null && qualifiedName.contains(DOT_STRING)) { // try if the last part defines a inner class String qualifiedNameInner = qualifiedName.substring(0, - qualifiedName.lastIndexOf(StringAndCharConstants.DOT)) + "$" - + qualifiedName.substring(qualifiedName.lastIndexOf(StringAndCharConstants.DOT) + 1); + qualifiedName.lastIndexOf(StringAndCharConstants.DOT)) + "$" + + qualifiedName.substring(qualifiedName.lastIndexOf(StringAndCharConstants.DOT) + 1); try { myType = pmdClassLoader.loadClass(qualifiedNameInner); } catch (Exception e) { @@ -744,6 +742,7 @@ private String getClassName(ASTCompilationUnit node) { /** * If the outer class wasn't found then we'll get in here + * @param node node */ private void populateImports(ASTCompilationUnit node) { List theImportDeclarations = node.findChildrenOfType(ASTImportDeclaration.class); diff --git a/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/AbstractAliXpathRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/AbstractAliXpathRule.java new file mode 100644 index 000000000..27bc981ea --- /dev/null +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/AbstractAliXpathRule.java @@ -0,0 +1,102 @@ +/* + * 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.xenoamess.p3c.pmd.lang; + +import com.xenoamess.p3c.pmd.I18nResources; +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils; +import net.sourceforge.pmd.lang.ast.Node; +import net.sourceforge.pmd.lang.rule.XPathRule; + +/** + * @author caikang + * @date 2017/05/25 + */ +public abstract class AbstractAliXpathRule extends XPathRule { + @Override + public void setDescription(String description) { + super.setDescription(I18nResources.getMessageWithExceptionHandled(description)); + } + + @Override + public void setMessage(String message) { + super.setMessage(I18nResources.getMessageWithExceptionHandled(message)); + } + + @Override + public void addViolationWithMessage(Object data, Node node, String message) { + if (ViolationUtils.shouldIgnoreViolation(this.getClass(), node)) { + return; + } + super.addViolationWithMessage(data, node, I18nResources.getMessageWithExceptionHandled(message)); + } + + @Override + public void addViolationWithMessage(Object data, Node node, String message, Object[] args) { + if (ViolationUtils.shouldIgnoreViolation(this.getClass(), node)) { + return; + } + super.addViolationWithMessage(data, node, + String.format(I18nResources.getMessageWithExceptionHandled(message), args)); + } + + /** + * @see net.sourceforge.pmd.lang.rule.RuleViolationFactory#addViolation(net.sourceforge.pmd.RuleContext, net.sourceforge.pmd.Rule, Node, String, + * Object[]) + */ + @Override + public void addViolation(Object data, Node node) { + if (ViolationUtils.shouldIgnoreViolation(this.getClass(), node)) { + return; + } + super.addViolation(data, node); + } + + /** + * @see net.sourceforge.pmd.lang.rule.RuleViolationFactory#addViolation(net.sourceforge.pmd.RuleContext, net.sourceforge.pmd.Rule, Node, String, + * Object[]) + */ + @Override + public void addViolation(Object data, Node node, String arg) { + if (ViolationUtils.shouldIgnoreViolation(this.getClass(), node)) { + return; + } + super.addViolation(data, node, arg); + } + + /** + * @see net.sourceforge.pmd.lang.rule.RuleViolationFactory#addViolation(net.sourceforge.pmd.RuleContext, net.sourceforge.pmd.Rule, Node, String, + * Object[]) + */ + @Override + public void addViolation(Object data, Node node, Object[] args) { + if (ViolationUtils.shouldIgnoreViolation(this.getClass(), node)) { + return; + } + super.addViolation(data, node, args); + } + + /** + * @see net.sourceforge.pmd.lang.rule.RuleViolationFactory#addViolation(net.sourceforge.pmd.RuleContext, net.sourceforge.pmd.Rule, Node, String, + * Object[]) + */ + @Override + public void addViolationWithMessage(Object data, Node node, String message, int beginLine, int endLine) { + if (ViolationUtils.shouldIgnoreViolation(this.getClass(), node)) { + return; + } + super.addViolationWithMessage(data, node, message, beginLine, endLine); + } +} diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/AbstractAliRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/AbstractAliRule.java similarity index 77% rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/AbstractAliRule.java rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/AbstractAliRule.java index bf595819b..721d3d273 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/AbstractAliRule.java +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/AbstractAliRule.java @@ -13,20 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.p3c.pmd.lang.java.rule; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import com.alibaba.p3c.pmd.I18nResources; -import com.alibaba.p3c.pmd.fix.FixClassTypeResolver; +package com.xenoamess.p3c.pmd.lang.java.rule; +import com.xenoamess.p3c.pmd.I18nResources; +import com.xenoamess.p3c.pmd.fix.FixClassTypeResolver; +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule; import org.apache.commons.lang3.StringUtils; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + /** * re calculate node type * @@ -43,7 +43,7 @@ public abstract class AbstractAliRule extends AbstractJavaRule { @Override public Object visit(ASTCompilationUnit node, Object data) { // Each CompilationUnit will be scanned only once by custom type resolver. - String sourceCodeFilename = ((RuleContext)data).getSourceCodeFilename(); + String sourceCodeFilename = ((RuleContext) data).getSourceCodeFilename(); // Do type resolve if file name is empty(unit tests). if (StringUtils.isBlank(sourceCodeFilename) || EMPTY_FILE_NAME.equals(sourceCodeFilename)) { @@ -72,13 +72,26 @@ public void setMessage(String message) { @Override public void addViolationWithMessage(Object data, Node node, String message) { - super.addViolationWithMessage(data, node, I18nResources.getMessageWithExceptionHandled(message)); + if (ViolationUtils.shouldIgnoreViolation(this.getClass(), node)) { + return; + } + super.addViolationWithMessage( + data, + node, + I18nResources.getMessageWithExceptionHandled(message) + ); } @Override public void addViolationWithMessage(Object data, Node node, String message, Object[] args) { - super.addViolationWithMessage(data, node, - String.format(I18nResources.getMessageWithExceptionHandled(message), args)); + if (ViolationUtils.shouldIgnoreViolation(this.getClass(), node)) { + return; + } + super.addViolationWithMessage( + data, + node, + String.format(I18nResources.getMessageWithExceptionHandled(message), args) + ); } private void resolveType(ASTCompilationUnit node, Object data) { diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/AbstractPojoRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/AbstractPojoRule.java similarity index 80% rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/AbstractPojoRule.java rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/AbstractPojoRule.java index fb59ee912..005e805cb 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/AbstractPojoRule.java +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/AbstractPojoRule.java @@ -13,15 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.p3c.pmd.lang.java.rule; - -import java.util.List; - -import com.alibaba.p3c.pmd.lang.java.util.PojoUtils; +package com.xenoamess.p3c.pmd.lang.java.rule; +import com.xenoamess.p3c.pmd.lang.java.util.PojoUtils; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit; +import java.util.List; + /** * Base class for POJO * @@ -50,13 +49,13 @@ public Object visit(ASTCompilationUnit node, Object data) { /** * check contains POJO * @param node compilation unit - * @return + * @return ifHasPojoInJavaFile */ private boolean hasPojoInJavaFile(ASTCompilationUnit node) { - List klasses = node.findDescendantsOfType( + List astClassOrInterfaceDeclarations = node.findDescendantsOfType( ASTClassOrInterfaceDeclaration.class); - for (ASTClassOrInterfaceDeclaration klass : klasses) { - if (isPojo(klass)) { + for (ASTClassOrInterfaceDeclaration astClassOrInterfaceDeclaration : astClassOrInterfaceDeclarations) { + if (isPojo(astClassOrInterfaceDeclaration)) { return true; } } 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/xenoamess/p3c/pmd/lang/java/rule/comment/AbstractAliCommentRule.java similarity index 61% rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/AbstractAliCommentRule.java rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/comment/AbstractAliCommentRule.java index d56ea5b98..9b4075ac9 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/AbstractAliCommentRule.java +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/comment/AbstractAliCommentRule.java @@ -13,10 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.p3c.pmd.lang.java.rule.comment; - -import com.alibaba.p3c.pmd.I18nResources; +package com.xenoamess.p3c.pmd.lang.java.rule.comment; +import com.xenoamess.p3c.pmd.I18nResources; +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.rule.documentation.AbstractCommentRule; @@ -24,7 +24,7 @@ * @author caikang * @date 2017/06/21 */ -public class AbstractAliCommentRule extends AbstractCommentRule { +public abstract class AbstractAliCommentRule extends AbstractCommentRule { @Override public void setDescription(String description) { super.setDescription(I18nResources.getMessageWithExceptionHandled(description)); @@ -37,12 +37,27 @@ public void setMessage(String message) { @Override public void addViolationWithMessage(Object data, Node node, String message) { - super.addViolationWithMessage(data, node, I18nResources.getMessageWithExceptionHandled(message)); + if (ViolationUtils.shouldIgnoreViolation(this.getClass(), node)) { + return; + } + super.addViolationWithMessage( + data, + node, + I18nResources.getMessageWithExceptionHandled(message) + ); } @Override public void addViolationWithMessage(Object data, Node node, String message, Object[] args) { - super.addViolationWithMessage(data, node, - String.format(I18nResources.getMessageWithExceptionHandled(message), args)); + if (ViolationUtils.shouldIgnoreViolation(this.getClass(), node)) { + return; + } + super.addViolationWithMessage( + data, + node, + String.format(I18nResources.getMessageWithExceptionHandled(message), + args + ) + ); } } diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/AbstractMethodOrInterfaceMethodMustUseJavadocRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/comment/AbstractMethodOrInterfaceMethodMustUseJavadocRule.java similarity index 76% rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/AbstractMethodOrInterfaceMethodMustUseJavadocRule.java rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/comment/AbstractMethodOrInterfaceMethodMustUseJavadocRule.java index 5eb3dfc61..03ba99ed5 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/AbstractMethodOrInterfaceMethodMustUseJavadocRule.java +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/comment/AbstractMethodOrInterfaceMethodMustUseJavadocRule.java @@ -13,14 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.p3c.pmd.lang.java.rule.comment; - -import java.util.List; -import java.util.regex.Pattern; - -import com.alibaba.p3c.pmd.I18nResources; -import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils; +package com.xenoamess.p3c.pmd.lang.java.rule.comment; +import com.xenoamess.p3c.pmd.I18nResources; +import com.xenoamess.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.ASTCompilationUnit; @@ -32,6 +28,9 @@ import net.sourceforge.pmd.lang.java.ast.FormalComment; import org.jaxen.JaxenException; +import java.util.List; +import java.util.regex.Pattern; + /** * [Mandatory] Abstract methods (including methods in interface) should be commented by Javadoc. * Javadoc should include method instruction, description of parameters, return values and possible exception. @@ -42,15 +41,16 @@ public class AbstractMethodOrInterfaceMethodMustUseJavadocRule extends AbstractAliCommentRule { private static final String METHOD_IN_INTERFACE_XPATH = - "./ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/MethodDeclaration"; + "./ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/MethodDeclaration"; private static final String METHOD_VARIABLE_DECLARATOR_XPATH - = "./MethodDeclarator/FormalParameters/FormalParameter/VariableDeclaratorId"; + = "./MethodDeclarator/FormalParameters/FormalParameter/VariableDeclaratorId"; private static final String MESSAGE_KEY_PREFIX - = "java.comment.AbstractMethodOrInterfaceMethodMustUseJavadocRule.violation.msg"; + = "java.comment.AbstractMethodOrInterfaceMethodMustUseJavadocRule.violation.msg"; private static final Pattern EMPTY_CONTENT_PATTERN = Pattern.compile("[/*\\n\\r\\s]+(@.*)?", Pattern.DOTALL); private static final Pattern RETURN_PATTERN = Pattern.compile(".*@return.*", Pattern.DOTALL); + private static final Pattern INHERIT_DOC_PATTERN = Pattern.compile(".*@inheritDoc.*", Pattern.DOTALL); @Override public Object visit(ASTClassOrInterfaceDeclaration decl, Object data) { @@ -61,10 +61,10 @@ public Object visit(ASTClassOrInterfaceDeclaration decl, Object data) { continue; } Comment comment = method.comment(); - if (null == comment || !(comment instanceof FormalComment)) { + if (!(comment instanceof FormalComment)) { ViolationUtils.addViolationWithPrecisePosition(this, method, data, - I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".abstract", - method.getMethodName())); + I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".abstract", + method.getName())); } else { this.checkMethodCommentFormat(method, data); } @@ -78,16 +78,16 @@ public Object visit(ASTClassOrInterfaceDeclaration decl, Object data) { methodNodes = decl.findChildNodesWithXPath(METHOD_IN_INTERFACE_XPATH); } catch (JaxenException e) { throw new RuntimeException("XPath expression " + METHOD_IN_INTERFACE_XPATH - + " failed: " + e.getLocalizedMessage(), e); + + " failed: " + e.getLocalizedMessage(), e); } for (Node node : methodNodes) { - ASTMethodDeclaration method = (ASTMethodDeclaration)node; + ASTMethodDeclaration method = (ASTMethodDeclaration) node; Comment comment = method.comment(); - if (null == comment || !(comment instanceof FormalComment)) { + if (!(comment instanceof FormalComment)) { ViolationUtils.addViolationWithPrecisePosition(this, method, data, - I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".interface", - method.getMethodName())); + I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".interface", + method.getName())); } else { this.checkMethodCommentFormat(method, data); } @@ -102,8 +102,15 @@ public void checkMethodCommentFormat(ASTMethodDeclaration method, Object data) { // method instruction if (EMPTY_CONTENT_PATTERN.matcher(commentContent).matches()) { ViolationUtils.addViolationWithPrecisePosition(this, method, data, - I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".desc", - method.getMethodName())); + I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".desc", + method.getName())); + } + + // if has @inheritDoc in javadoc of this function, + // then the things not listed are inherited from super function, + // thus legal. + if (INHERIT_DOC_PATTERN.matcher(commentContent).matches()) { + return; } // description of parameters @@ -112,18 +119,18 @@ public void checkMethodCommentFormat(ASTMethodDeclaration method, Object data) { variableDeclaratorIds = method.findChildNodesWithXPath(METHOD_VARIABLE_DECLARATOR_XPATH); } catch (JaxenException e) { throw new RuntimeException( - "XPath expression " + METHOD_VARIABLE_DECLARATOR_XPATH + " failed: " + e.getLocalizedMessage(), e); + "XPath expression " + METHOD_VARIABLE_DECLARATOR_XPATH + " failed: " + e.getLocalizedMessage(), e); } for (Node variableDeclaratorId : variableDeclaratorIds) { - ASTVariableDeclaratorId param = (ASTVariableDeclaratorId)variableDeclaratorId; + ASTVariableDeclaratorId param = (ASTVariableDeclaratorId) variableDeclaratorId; String paramName = param.getImage(); Pattern paramNamePattern = Pattern.compile(".*@param\\s+" + paramName + ".*", Pattern.DOTALL); if (!paramNamePattern.matcher(commentContent).matches()) { ViolationUtils.addViolationWithPrecisePosition(this, method, data, - I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".parameter", - method.getMethodName(), paramName)); + I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".parameter", + method.getName(), paramName)); } } @@ -131,8 +138,8 @@ public void checkMethodCommentFormat(ASTMethodDeclaration method, Object data) { if (!method.isVoid() && !RETURN_PATTERN.matcher(commentContent).matches()) { ViolationUtils.addViolationWithPrecisePosition(this, method, data, - I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".return", - method.getMethodName())); + I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".return", + method.getName())); } // possible exception @@ -142,12 +149,12 @@ public void checkMethodCommentFormat(ASTMethodDeclaration method, Object data) { for (ASTName exception : exceptions) { String exceptionName = exception.getImage(); Pattern exceptionPattern = Pattern.compile(".*@throws\\s+" - + exceptionName + ".*", Pattern.DOTALL); + + exceptionName + ".*", Pattern.DOTALL); if (!exceptionPattern.matcher(commentContent).matches()) { ViolationUtils.addViolationWithPrecisePosition(this, method, data, - I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".exception", - method.getMethodName(), exceptionName)); + I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".exception", + method.getName(), exceptionName)); } } } diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/AvoidCommentBehindStatementRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/comment/AvoidCommentBehindStatementRule.java similarity index 81% rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/AvoidCommentBehindStatementRule.java rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/comment/AvoidCommentBehindStatementRule.java index d67ec7055..4bc317079 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/AvoidCommentBehindStatementRule.java +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/comment/AvoidCommentBehindStatementRule.java @@ -13,16 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.p3c.pmd.lang.java.rule.comment; - -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.util.NodeSortUtils; +package com.xenoamess.p3c.pmd.lang.java.rule.comment; +import com.xenoamess.p3c.pmd.I18nResources; +import com.xenoamess.p3c.pmd.lang.java.rule.util.NodeSortUtils; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit; import net.sourceforge.pmd.lang.java.ast.ASTEnumConstant; @@ -31,6 +25,11 @@ import net.sourceforge.pmd.lang.java.ast.AbstractJavaNode; import net.sourceforge.pmd.lang.java.ast.Comment; +import java.util.List; +import java.util.Map.Entry; +import java.util.SortedMap; +import java.util.TreeMap; + /** * [Mandatory] Single line comments in a method should be put above the code to be commented, by using // and * multiple lines by using \/* *\/. Alignment for comments should be noticed carefully. @@ -48,14 +47,14 @@ public Object visit(ASTCompilationUnit cUnit, Object data) { for (Entry entry : itemsByLineNumber.entrySet()) { Node value = entry.getValue(); if (value instanceof AbstractJavaNode) { - lastNode = (AbstractJavaNode)value; + lastNode = (AbstractJavaNode) value; } else if (value instanceof Comment) { - Comment comment = (Comment)value; + Comment comment = (Comment) value; if (lastNode != null && (comment.getBeginLine() == lastNode.getBeginLine()) - && (comment.getEndColumn() > lastNode.getBeginColumn())) { + && (comment.getEndColumn() > lastNode.getBeginColumn())) { addViolationWithMessage(data, lastNode, - I18nResources.getMessage("java.comment.AvoidCommentBehindStatementRule.violation.msg"), - comment.getBeginLine(), comment.getEndLine()); + I18nResources.getMessage("java.comment.AvoidCommentBehindStatementRule.violation.msg"), + comment.getBeginLine(), comment.getEndLine()); } } } @@ -79,12 +78,12 @@ protected SortedMap orderedCommentsAndExpressions(ASTCompilationU // filed declaration nodes List fieldNodes = - cUnit.findDescendantsOfType(ASTFieldDeclaration.class); + cUnit.findDescendantsOfType(ASTFieldDeclaration.class); NodeSortUtils.addNodesToSortedMap(itemsByLineNumber, fieldNodes); // enum constant nodes List enumConstantNodes = - cUnit.findDescendantsOfType(ASTEnumConstant.class); + cUnit.findDescendantsOfType(ASTEnumConstant.class); NodeSortUtils.addNodesToSortedMap(itemsByLineNumber, enumConstantNodes); NodeSortUtils.addNodesToSortedMap(itemsByLineNumber, cUnit.getComments()); 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/xenoamess/p3c/pmd/lang/java/rule/comment/ClassMustHaveAuthorRule.java similarity index 90% rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/ClassMustHaveAuthorRule.java rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/comment/ClassMustHaveAuthorRule.java index b0c29f5fe..46369d8ae 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/ClassMustHaveAuthorRule.java +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/comment/ClassMustHaveAuthorRule.java @@ -13,16 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -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; +package com.xenoamess.p3c.pmd.lang.java.rule.comment; +import com.xenoamess.p3c.pmd.I18nResources; +import com.xenoamess.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; @@ -31,6 +25,11 @@ import net.sourceforge.pmd.lang.java.ast.AbstractJavaNode; import net.sourceforge.pmd.lang.java.ast.Comment; +import java.util.List; +import java.util.SortedMap; +import java.util.TreeMap; +import java.util.regex.Pattern; + /** * [Mandatory] Every class should include information of author(s) and date. * @@ -40,7 +39,7 @@ public class ClassMustHaveAuthorRule extends AbstractAliCommentRule { private static final Pattern AUTHOR_PATTERN = Pattern.compile(".*@[Aa]uthor.*", - Pattern.DOTALL | Pattern.CASE_INSENSITIVE); + Pattern.DOTALL | Pattern.CASE_INSENSITIVE); private static final String MESSAGE_KEY_PREFIX = "java.comment.ClassMustHaveAuthorRule.violation.msg"; @@ -96,14 +95,14 @@ protected SortedMap orderedCommentsAndDeclarations(ASTCompilation SortedMap itemsByLineNumber = new TreeMap<>(); List packageDecl = cUnit - .findDescendantsOfType(ASTClassOrInterfaceDeclaration.class); + .findDescendantsOfType(ASTClassOrInterfaceDeclaration.class); addDeclarations(itemsByLineNumber, packageDecl); List enumDecl = cUnit.findDescendantsOfType(ASTEnumDeclaration.class); addDeclarations(itemsByLineNumber, enumDecl); List annotationDecl = cUnit - .findDescendantsOfType(ASTAnnotationTypeDeclaration.class); + .findDescendantsOfType(ASTAnnotationTypeDeclaration.class); addDeclarations(itemsByLineNumber, annotationDecl); addDeclarations(itemsByLineNumber, cUnit.getComments()); @@ -127,13 +126,13 @@ public void checkAuthorComment(AbstractJavaNode decl, Object data) { Comment comment = decl.comment(); if (null == comment) { ViolationUtils.addViolationWithPrecisePosition(this, decl, data, - I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".comment", decl.getImage())); + I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".comment", decl.getImage())); } else { String commentContent = comment.getImage(); boolean hasAuthor = AUTHOR_PATTERN.matcher(commentContent).matches(); if (!hasAuthor) { ViolationUtils.addViolationWithPrecisePosition(this, decl, data, - I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".author", decl.getImage())); + I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".author", decl.getImage())); } } } 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/xenoamess/p3c/pmd/lang/java/rule/comment/CommentsMustBeJavadocFormatRule.java similarity index 85% rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/CommentsMustBeJavadocFormatRule.java rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/comment/CommentsMustBeJavadocFormatRule.java index 7cf5844fb..2c286495f 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/CommentsMustBeJavadocFormatRule.java +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/comment/CommentsMustBeJavadocFormatRule.java @@ -13,19 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.p3c.pmd.lang.java.rule.comment; +package com.xenoamess.p3c.pmd.lang.java.rule.comment; -import java.util.ArrayList; -import java.util.Iterator; -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.util.NodeSortUtils; - -import com.alibaba.p3c.pmd.lang.java.util.VariableUtils; +import com.xenoamess.p3c.pmd.I18nResources; +import com.xenoamess.p3c.pmd.lang.java.rule.util.NodeSortUtils; +import com.xenoamess.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; @@ -44,6 +36,13 @@ import net.sourceforge.pmd.lang.java.ast.Token; import org.apache.commons.lang3.StringUtils; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map.Entry; +import java.util.SortedMap; +import java.util.TreeMap; + /** * [Mandatory] Javadoc should be used for classes, class variables and methods. * The format should be '\/** comment *\/', rather than '// xxx'. @@ -58,30 +57,30 @@ public class CommentsMustBeJavadocFormatRule extends AbstractAliCommentRule { @Override public Object visit(final ASTClassOrInterfaceDeclaration decl, Object data) { checkComment(decl, data, () -> I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".class", - decl.getImage())); + decl.getImage())); return super.visit(decl, data); } @Override public Object visit(final ASTConstructorDeclaration decl, Object data) { checkComment(decl, data, () -> { - String constructorName = ((Token)decl.jjtGetFirstToken()).image; - if (decl.getFormalParameters().getParameterCount() == 0) { + String constructorName = ((Token) decl.jjtGetFirstToken()).image; + if (decl.getFormalParameters().size() == 0) { return I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".constructor.default", - constructorName); + constructorName); } List formalParameters = decl.getFormalParameters() - .findChildrenOfType(ASTFormalParameter.class); + .findChildrenOfType(ASTFormalParameter.class); List strings = new ArrayList<>(formalParameters.size()); for (ASTFormalParameter formalParameter : formalParameters) { strings.add(formalParameter.jjtGetFirstToken().toString() + " " - + formalParameter.jjtGetLastToken().toString()); + + formalParameter.jjtGetLastToken().toString()); } return I18nResources - .getMessage(MESSAGE_KEY_PREFIX + ".constructor.parameter", - constructorName, - StringUtils.join(strings, ",")); + .getMessage(MESSAGE_KEY_PREFIX + ".constructor.parameter", + constructorName, + StringUtils.join(strings, ",")); }); return super.visit(decl, data); } @@ -89,21 +88,21 @@ public Object visit(final ASTConstructorDeclaration decl, Object data) { @Override public Object visit(final ASTMethodDeclaration decl, Object data) { checkComment(decl, data, () -> I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".method", - decl.getMethodName())); + decl.getName())); return super.visit(decl, data); } @Override public Object visit(final ASTFieldDeclaration decl, Object data) { checkComment(decl, data, () -> I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".field", - VariableUtils.getVariableName(decl))); + VariableUtils.getVariableName(decl))); return super.visit(decl, data); } @Override public Object visit(final ASTEnumDeclaration decl, Object data) { checkComment(decl, data, () -> I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".enum", - decl.getImage())); + decl.getImage())); return super.visit(decl, data); } @@ -118,7 +117,7 @@ private void checkComment(AbstractJavaAccessNode decl, Object data, MessageMaker Comment comment = decl.comment(); if (comment instanceof SingleLineComment || comment instanceof MultiLineComment) { addViolationWithMessage(data, decl, - maker.make(), comment.getBeginLine(), comment.getEndLine()); + maker.make(), comment.getBeginLine(), comment.getEndLine()); } } @@ -133,7 +132,7 @@ protected void assignCommentsToDeclarations(ASTCompilationUnit cUnit) { Node value = entry.getValue(); if (value instanceof AbstractJavaNode) { - AbstractJavaNode node = (AbstractJavaNode)value; + AbstractJavaNode node = (AbstractJavaNode) value; // skip annotation node, we will deal with it later. if (node instanceof ASTAnnotation) { @@ -148,7 +147,7 @@ protected void assignCommentsToDeclarations(ASTCompilationUnit cUnit) { lastNode = node; } else if (value instanceof Comment) { - lastComment = (Comment)value; + lastComment = (Comment) value; } } } @@ -163,7 +162,7 @@ protected SortedMap orderedComments(ASTCompilationUnit cUnit) { NodeSortUtils.addNodesToSortedMap(itemsByLineNumber, annotations); List classDecl = - cUnit.findDescendantsOfType(ASTClassOrInterfaceDeclaration.class); + cUnit.findDescendantsOfType(ASTClassOrInterfaceDeclaration.class); NodeSortUtils.addNodesToSortedMap(itemsByLineNumber, classDecl); List fields = cUnit.findDescendantsOfType(ASTFieldDeclaration.class); @@ -181,9 +180,10 @@ protected SortedMap orderedComments(ASTCompilationUnit cUnit) { return itemsByLineNumber; } - private boolean isCommentOneLineBefore(SortedMap items, Comment lastComment, Node lastNode, Node node) { + private boolean isCommentOneLineBefore(SortedMap items, Comment lastComment, Node lastNode, + Node node) { ASTClassOrInterfaceBodyDeclaration parentClass = - node.getFirstParentOfType(ASTClassOrInterfaceBodyDeclaration.class); + node.getFirstParentOfType(ASTClassOrInterfaceBodyDeclaration.class); // Skip comments inside inner class. if (parentClass != null && parentClass.isAnonymousInnerClass()) { @@ -197,7 +197,7 @@ private boolean isCommentOneLineBefore(SortedMap items, Comment l // check if there is nothing in the middle except annotations. SortedMap subMap = items.subMap(NodeSortUtils.generateIndex(lastComment), - NodeSortUtils.generateIndex(node)); + NodeSortUtils.generateIndex(node)); Iterator> iter = subMap.entrySet().iterator(); // skip the first comment node. diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/EnumConstantsMustHaveCommentRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/comment/EnumConstantsMustHaveCommentRule.java similarity index 81% rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/EnumConstantsMustHaveCommentRule.java rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/comment/EnumConstantsMustHaveCommentRule.java index 7e795ee36..2acb2f735 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/EnumConstantsMustHaveCommentRule.java +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/comment/EnumConstantsMustHaveCommentRule.java @@ -13,21 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.p3c.pmd.lang.java.rule.comment; - -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.util.NodeSortUtils; +package com.xenoamess.p3c.pmd.lang.java.rule.comment; +import com.xenoamess.p3c.pmd.I18nResources; +import com.xenoamess.p3c.pmd.lang.java.rule.util.NodeSortUtils; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit; import net.sourceforge.pmd.lang.java.ast.ASTEnumConstant; import net.sourceforge.pmd.lang.java.ast.ASTEnumDeclaration; +import java.util.List; +import java.util.Map.Entry; +import java.util.SortedMap; +import java.util.TreeMap; + /** * [Mandatory] All enumeration type fields should be commented as Javadoc style. * @@ -49,11 +48,11 @@ public Object visit(ASTCompilationUnit cUnit, Object data) { if (value instanceof ASTEnumDeclaration) { isPreviousEnumDecl = true; } else if (value instanceof ASTEnumConstant && isPreviousEnumDecl) { - Node enumBody = value.jjtGetParent(); - Node enumDeclaration = enumBody.jjtGetParent(); + Node enumBody = value.getParent(); + Node enumDeclaration = enumBody.getParent(); addViolationWithMessage(data, enumBody, - I18nResources.getMessage("java.comment.EnumConstantsMustHaveCommentRule.violation.msg", - enumDeclaration.getImage())); + I18nResources.getMessage("java.comment.EnumConstantsMustHaveCommentRule.violation.msg", + enumDeclaration.getImage())); isPreviousEnumDecl = false; } else { isPreviousEnumDecl = false; @@ -69,8 +68,8 @@ private SortedMap orderedCommentsAndEnumDeclarations(ASTCompilati List enumDecl = cUnit.findDescendantsOfType(ASTEnumDeclaration.class); NodeSortUtils.addNodesToSortedMap(itemsByLineNumber, enumDecl); - List contantDecl = cUnit.findDescendantsOfType(ASTEnumConstant.class); - NodeSortUtils.addNodesToSortedMap(itemsByLineNumber, contantDecl); + List constantDecl = cUnit.findDescendantsOfType(ASTEnumConstant.class); + NodeSortUtils.addNodesToSortedMap(itemsByLineNumber, constantDecl); NodeSortUtils.addNodesToSortedMap(itemsByLineNumber, cUnit.getComments()); diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/RemoveCommentedCodeRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/comment/RemoveCommentedCodeRule.java similarity index 90% rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/RemoveCommentedCodeRule.java rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/comment/RemoveCommentedCodeRule.java index a880be6f5..efcf71546 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/RemoveCommentedCodeRule.java +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/comment/RemoveCommentedCodeRule.java @@ -13,16 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.p3c.pmd.lang.java.rule.comment; - -import java.util.List; -import java.util.Map.Entry; -import java.util.SortedMap; -import java.util.TreeMap; -import java.util.regex.Pattern; - -import com.alibaba.p3c.pmd.lang.java.rule.util.NodeSortUtils; +package com.xenoamess.p3c.pmd.lang.java.rule.comment; +import com.xenoamess.p3c.pmd.lang.java.rule.util.NodeSortUtils; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.ASTBlockStatement; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; @@ -34,6 +27,12 @@ import net.sourceforge.pmd.lang.java.ast.Comment; import net.sourceforge.pmd.lang.java.ast.JavaNode; +import java.util.List; +import java.util.Map.Entry; +import java.util.SortedMap; +import java.util.TreeMap; +import java.util.regex.Pattern; + /** * [Recommended] Codes or configuration that is noticed to be obsoleted should be resolutely removed from projects. * @@ -47,12 +46,12 @@ public class RemoveCommentedCodeRule extends AbstractAliCommentRule { private static final Pattern PRE_TAG_PATTERN = Pattern.compile(".*
          .*", Pattern.DOTALL);
           
               private static final Pattern IMPORT_PATTERN = Pattern.compile(".*import\\s(static\\s)?(\\w*\\.)*\\w*;.*",
          -        Pattern.DOTALL);
          +            Pattern.DOTALL);
           
               private static final Pattern FIELD_PATTERN = Pattern.compile(".*private\\s+(\\w*)\\s+(\\w*);.*", Pattern.DOTALL);
           
               private static final Pattern METHOD_PATTERN = Pattern.compile(
          -        ".*(public|protected|private)\\s+\\w+\\s+\\w+\\(.*\\)\\s+\\{.*", Pattern.DOTALL);
          +            ".*(public|protected|private)\\s+\\w+\\s+\\w+\\(.*\\)\\s+\\{.*", Pattern.DOTALL);
           
               /**
                * If string matches format ".xxx(.*);\n", then mark it as code.
          @@ -77,7 +76,7 @@ protected void checkCommentsBetweenDeclarations(ASTCompilationUnit cUnit, Object
                       Node value = entry.getValue();
           
                       if (value instanceof JavaNode) {
          -                JavaNode node = (JavaNode)value;
          +                JavaNode node = (JavaNode) value;
           
                           // add violation on the node after comment.
                           if (lastComment != null && isCommentBefore(lastComment, node)) {
          @@ -85,11 +84,11 @@ protected void checkCommentsBetweenDeclarations(ASTCompilationUnit cUnit, Object
                               if (!CommentPatternEnum.NONE.equals(commentPattern)) {
                                   // check statement pattern only in method
                                   boolean statementOutsideMethod = CommentPatternEnum.STATEMENT.equals(commentPattern)
          -                            && !(node instanceof ASTBlockStatement);
          +                                && !(node instanceof ASTBlockStatement);
                                   if (!statementOutsideMethod) {
                                       addViolationWithMessage(data, node, getMessage(),
          -                                lastComment.getBeginLine(),
          -                                lastComment.getEndLine());
          +                                    lastComment.getBeginLine(),
          +                                    lastComment.getEndLine());
                                   }
                               }
                               lastComment = null;
          @@ -100,7 +99,7 @@ protected void checkCommentsBetweenDeclarations(ASTCompilationUnit cUnit, Object
                           commentPattern = CommentPatternEnum.NONE;
           
                       } else if (value instanceof Comment) {
          -                lastComment = (Comment)value;
          +                lastComment = (Comment) value;
                           String content = lastComment.getImage();
           
                           if (!suppressWarning) {
          @@ -150,11 +149,11 @@ protected SortedMap orderedCommentsAndDeclarations(ASTCompilation
                   SortedMap itemsByLineNumber = new TreeMap<>();
           
                   List importDecl = cUnit
          -            .findDescendantsOfType(ASTImportDeclaration.class);
          +                .findDescendantsOfType(ASTImportDeclaration.class);
                   NodeSortUtils.addNodesToSortedMap(itemsByLineNumber, importDecl);
           
                   List classDecl = cUnit
          -            .findDescendantsOfType(ASTClassOrInterfaceDeclaration.class);
          +                .findDescendantsOfType(ASTClassOrInterfaceDeclaration.class);
                   NodeSortUtils.addNodesToSortedMap(itemsByLineNumber, classDecl);
           
                   List fields = cUnit.findDescendantsOfType(ASTFieldDeclaration.class);
          @@ -176,7 +175,7 @@ protected SortedMap orderedCommentsAndDeclarations(ASTCompilation
           
               private boolean isCommentBefore(Comment n1, Node n2) {
                   return n1.getEndLine() < n2.getBeginLine() || n1.getEndLine() == n2.getBeginLine()
          -            && n1.getEndColumn() < n2.getBeginColumn();
          +                && n1.getEndColumn() < n2.getBeginColumn();
               }
           
               enum CommentPatternEnum {
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/AvoidCallStaticSimpleDateFormatRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/AvoidCallStaticSimpleDateFormatRule.java
          similarity index 83%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/AvoidCallStaticSimpleDateFormatRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/AvoidCallStaticSimpleDateFormatRule.java
          index 6a6efea44..d8b921514 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/AvoidCallStaticSimpleDateFormatRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/AvoidCallStaticSimpleDateFormatRule.java
          @@ -13,15 +13,9 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.concurrent;
          -
          -import java.text.SimpleDateFormat;
          -import java.util.HashSet;
          -import java.util.Set;
          -import java.util.Stack;
          -
          -import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule;
          +package com.xenoamess.p3c.pmd.lang.java.rule.concurrent;
           
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
           import net.sourceforge.pmd.lang.ast.Node;
           import net.sourceforge.pmd.lang.dfa.DataFlowNode;
           import net.sourceforge.pmd.lang.dfa.StartOrEndDataFlowNode;
          @@ -36,9 +30,14 @@
           import net.sourceforge.pmd.lang.java.ast.AbstractJavaNode;
           import net.sourceforge.pmd.lang.java.ast.Token;
           
          -import static com.alibaba.p3c.pmd.lang.java.rule.util.NodeUtils.isLockNode;
          -import static com.alibaba.p3c.pmd.lang.java.rule.util.NodeUtils.isLockStatementExpression;
          -import static com.alibaba.p3c.pmd.lang.java.rule.util.NodeUtils.isUnLockStatementExpression;
          +import java.text.SimpleDateFormat;
          +import java.util.HashSet;
          +import java.util.Set;
          +import java.util.Stack;
          +
          +import static com.xenoamess.p3c.pmd.lang.java.rule.util.NodeUtils.isLockNode;
          +import static com.xenoamess.p3c.pmd.lang.java.rule.util.NodeUtils.isLockStatementExpression;
          +import static com.xenoamess.p3c.pmd.lang.java.rule.util.NodeUtils.isUnLockStatementExpression;
           
           /**
            * [Mandatory] SimpleDataFormat is unsafe, do not define it as a static variable.
          @@ -75,8 +74,8 @@ private void handleMethod(ASTMethodDeclaration methodDeclaration, Object data) {
                       Node node = stack.pop();
                       if (node instanceof ASTPrimaryExpression) {
                           addViolationWithMessage(data, node,
          -                    "java.concurrent.AvoidCallStaticSimpleDateFormatRule.violation.msg",
          -                    new Object[] {getExpressName((ASTPrimaryExpression)node)});
          +                        "java.concurrent.AvoidCallStaticSimpleDateFormatRule.violation.msg",
          +                        new Object[]{getExpressName((ASTPrimaryExpression) node)});
                       }
                   }
               }
          @@ -87,17 +86,17 @@ private void handleFlowNode(Stack stack, Set localSimpleDateFormat
                   }
                   // collect local variables of type SimpleDateFormat if match,then return
                   if (flowNode.getNode() instanceof ASTVariableDeclarator) {
          -            ASTVariableDeclarator variableDeclarator = (ASTVariableDeclarator)flowNode.getNode();
          +            ASTVariableDeclarator variableDeclarator = (ASTVariableDeclarator) flowNode.getNode();
                       if (variableDeclarator.getType() == SimpleDateFormat.class) {
                           ASTVariableDeclaratorId variableDeclaratorId =
          -                    variableDeclarator.getFirstChildOfType(ASTVariableDeclaratorId.class);
          +                        variableDeclarator.getFirstChildOfType(ASTVariableDeclaratorId.class);
                           localSimpleDateFormatNames.add(variableDeclaratorId.getImage());
                           return;
                       }
                   }
           
                   if (flowNode.getNode() instanceof ASTStatementExpression) {
          -            ASTStatementExpression statementExpression = (ASTStatementExpression)flowNode.getNode();
          +            ASTStatementExpression statementExpression = (ASTStatementExpression) flowNode.getNode();
                       if (isLockStatementExpression(statementExpression)) {
                           // add lock node
                           stack.push(flowNode.getNode());
          @@ -115,7 +114,7 @@ private void handleFlowNode(Stack stack, Set localSimpleDateFormat
                           return;
                       }
                   }
          -        AbstractJavaNode javaNode = (AbstractJavaNode)flowNode.getNode();
          +        AbstractJavaNode javaNode = (AbstractJavaNode) flowNode.getNode();
                   ASTPrimaryExpression flowPrimaryExpression = javaNode.getFirstDescendantOfType(ASTPrimaryExpression.class);
                   if (flowPrimaryExpression == null) {
                       return;
          @@ -136,10 +135,10 @@ private String getExpressName(ASTPrimaryExpression primaryExpression) {
               }
           
               private boolean isStaticSimpleDateFormatCall(
          -        ASTPrimaryExpression primaryExpression,
          -        Set localSimpleDateFormatNames
          +            ASTPrimaryExpression primaryExpression,
          +            Set localSimpleDateFormatNames
               ) {
          -        if (primaryExpression.jjtGetNumChildren() == 0) {
          +        if (primaryExpression.getNumChildren() == 0) {
                       return false;
                   }
                   ASTName name = primaryExpression.getFirstDescendantOfType(ASTName.class);
          @@ -152,12 +151,12 @@ private boolean isStaticSimpleDateFormatCall(
                   if (localSimpleDateFormatNames.contains(name.getNameDeclaration().getName())) {
                       return false;
                   }
          -        ASTPrimaryPrefix primaryPrefix = (ASTPrimaryPrefix)primaryExpression.jjtGetChild(0);
          +        ASTPrimaryPrefix primaryPrefix = (ASTPrimaryPrefix) primaryExpression.getChild(0);
                   if (primaryPrefix.getType() != SimpleDateFormat.class) {
                       return false;
                   }
           
          -        Token token = (Token)primaryPrefix.jjtGetLastToken();
          +        Token token = (Token) primaryPrefix.jjtGetLastToken();
                   return FORMAT_METHOD_NAME.equals(token.image);
               }
           
          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/xenoamess/p3c/pmd/lang/java/rule/concurrent/AvoidConcurrentCompetitionRandomRule.java
          similarity index 86%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/AvoidConcurrentCompetitionRandomRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/AvoidConcurrentCompetitionRandomRule.java
          index e5e66022d..95ee18e43 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/AvoidConcurrentCompetitionRandomRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/AvoidConcurrentCompetitionRandomRule.java
          @@ -13,15 +13,11 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.concurrent;
          +package com.xenoamess.p3c.pmd.lang.java.rule.concurrent;
           
          -import java.util.List;
          -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 com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
          +import com.xenoamess.p3c.pmd.lang.java.rule.util.NodeUtils;
          +import com.xenoamess.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;
          @@ -32,6 +28,9 @@
           import net.sourceforge.pmd.lang.java.ast.ASTPrimaryPrefix;
           import org.jaxen.JaxenException;
           
          +import java.util.List;
          +import java.util.Random;
          +
           /**
            * 6.13 [Recommended] Avoid using Random instance by multiple threads.
            * Although it is safe to share this instance, competition on the same seed will damage performance.
          @@ -43,7 +42,7 @@
           public class AvoidConcurrentCompetitionRandomRule extends AbstractAliRule {
           
               private static final String XPATH_TPL = "//StatementExpression/PrimaryExpression"
          -        + "/PrimaryPrefix/Name[starts-with(@Image,'%s.')]";
          +            + "/PrimaryPrefix/Name[starts-with(@Image,'%s.')]";
           
               private static final String MATH_RANDOM_METHOD = ".random";
           
          @@ -70,7 +69,7 @@ public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
                   }
                   for (ASTFieldDeclaration fieldDeclaration : fieldDeclarations) {
                       if (NodeUtils.getNodeType(fieldDeclaration) == Random.class
          -                && fieldDeclaration.isStatic()) {
          +                    && fieldDeclaration.isStatic()) {
                           checkRandom(fieldDeclaration, methodDeclarations, data);
                       }
                   }
          @@ -80,7 +79,7 @@ public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
               private void checkMathRandom(List methodDeclarations, Object data) {
                   for (ASTMethodDeclaration methodDeclaration : methodDeclarations) {
                       List primaryPrefixes
          -                = methodDeclaration.findDescendantsOfType(ASTPrimaryPrefix.class);
          +                    = methodDeclaration.findDescendantsOfType(ASTPrimaryPrefix.class);
                       if (primaryPrefixes == null || primaryPrefixes.isEmpty()) {
                           continue;
                       }
          @@ -93,24 +92,24 @@ private void checkMathRandom(List methodDeclarations, Obje
                               continue;
                           }
                           addViolationWithMessage(data, primaryPrefix,
          -                    MESSAGE_KEY_PREFIX + ".violation.msg.math.random");
          +                        MESSAGE_KEY_PREFIX + ".violation.msg.math.random");
                       }
                   }
               }
           
               private void checkRandom(ASTFieldDeclaration fieldDeclaration, List methodDeclarations,
          -        Object data) {
          +                             Object data) {
                   for (ASTMethodDeclaration methodDeclaration : methodDeclarations) {
                       try {
                           List nodes = methodDeclaration.findChildNodesWithXPath(String.format(XPATH_TPL,
          -                    VariableUtils.getVariableName(fieldDeclaration)));
          +                        VariableUtils.getVariableName(fieldDeclaration)));
                           if (nodes == null || nodes.isEmpty()) {
                               continue;
                           }
                           for (Node rvNode : nodes) {
                               addViolationWithMessage(data, rvNode,
          -                        MESSAGE_KEY_PREFIX + ".violation.msg.random",
          -                        new Object[] {rvNode.getImage()});
          +                            MESSAGE_KEY_PREFIX + ".violation.msg.random",
          +                            new Object[]{rvNode.getImage()});
                           }
                       } catch (JaxenException ignore) {
                       }
          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/xenoamess/p3c/pmd/lang/java/rule/concurrent/AvoidManuallyCreateThreadRule.java
          similarity index 91%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/AvoidManuallyCreateThreadRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/AvoidManuallyCreateThreadRule.java
          index ad11f3771..c7b1e5c00 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/AvoidManuallyCreateThreadRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/AvoidManuallyCreateThreadRule.java
          @@ -13,14 +13,10 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.concurrent;
          -
          -import java.util.List;
          -import java.util.concurrent.ThreadFactory;
          -
          -import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule;
          -import com.alibaba.p3c.pmd.lang.java.rule.util.NodeUtils;
          +package com.xenoamess.p3c.pmd.lang.java.rule.concurrent;
           
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
          +import com.xenoamess.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;
          @@ -37,6 +33,9 @@
           import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclarator;
           import net.sourceforge.pmd.lang.java.ast.Token;
           
          +import java.util.List;
          +import java.util.concurrent.ThreadFactory;
          +
           /**
            * [Mandatory] Threads should be provided by thread pools. Explicitly creating threads is not allowed.
            * Note: Using thread pool can reduce the time of creating and destroying thread and save system resource.
          @@ -86,7 +85,7 @@ public Object visit(ASTAllocationExpression node, Object data) {
                   }
                   //implements of ThreadFactory
                   boolean isThreadFactory = (checkForNamingClass(node) || threadFactoryVariable(node))
          -            && isInPrimaryOrProtectedMethod(node);
          +                && isInPrimaryOrProtectedMethod(node);
                   if (isThreadFactory) {
                       return super.visit(node, data);
                   }
          @@ -98,7 +97,7 @@ private boolean isAddShutdownHook(ASTAllocationExpression node) {
                   if (blockStatement == null) {
                       return false;
                   }
          -        Token token = (Token)blockStatement.jjtGetFirstToken();
          +        Token token = (Token) blockStatement.jjtGetFirstToken();
                   return Runtime.class.getSimpleName().equals(token.image);
               }
           
          @@ -124,19 +123,19 @@ private boolean isInNewThreadMethod(ASTAllocationExpression node) {
                   if (!returnThread(methodDeclaration)) {
                       return false;
                   }
          -        if (!METHOD_NEW_THREAD.equals(methodDeclaration.getMethodName())) {
          +        if (!METHOD_NEW_THREAD.equals(methodDeclaration.getName())) {
                       return false;
                   }
                   List parameters = methodDeclaration.getFirstDescendantOfType(ASTFormalParameters.class)
          -            .findChildrenOfType(ASTFormalParameter.class);
          +                .findChildrenOfType(ASTFormalParameter.class);
                   return parameters.size() == 1
          -            && parameters.get(0).getFirstChildOfType(ASTType.class).getType() == Runnable.class;
          +                && parameters.get(0).getFirstChildOfType(ASTType.class).getType() == Runnable.class;
               }
           
               private boolean isInPrimaryOrProtectedMethod(ASTAllocationExpression node) {
                   ASTMethodDeclaration methodDeclaration = node.getFirstParentOfType(ASTMethodDeclaration.class);
                   return methodDeclaration != null && returnThread(methodDeclaration) && (methodDeclaration.isPrivate()
          -            || methodDeclaration.isProtected());
          +                || methodDeclaration.isProtected());
               }
           
               private boolean returnThread(ASTMethodDeclaration methodDeclaration) {
          @@ -152,7 +151,7 @@ private Object addViolationAndReturn(ASTAllocationExpression node, Object data)
           
               private boolean checkForNamingClass(ASTAllocationExpression node) {
                   ASTClassOrInterfaceDeclaration classOrInterfaceDeclaration =
          -            node.getFirstParentOfType(ASTClassOrInterfaceDeclaration.class);
          +                node.getFirstParentOfType(ASTClassOrInterfaceDeclaration.class);
                   if (classOrInterfaceDeclaration == null) {
                       return false;
                   }
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/AvoidUseTimerRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/AvoidUseTimerRule.java
          similarity index 89%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/AvoidUseTimerRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/AvoidUseTimerRule.java
          index 4eb4ccc62..8d56ff97b 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/AvoidUseTimerRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/AvoidUseTimerRule.java
          @@ -13,16 +13,15 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.concurrent;
          -
          -import java.util.Timer;
          -
          -import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule;
          +package com.xenoamess.p3c.pmd.lang.java.rule.concurrent;
           
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
           import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression;
           import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclarator;
           import net.sourceforge.pmd.lang.java.ast.AbstractJavaTypeNode;
           
          +import java.util.Timer;
          +
           /**
            * [Mandatory] Run multiple TimeTask by using ScheduledExecutorService rather than Timer
            * because Timer will kill all running threads in case of failing to catch exception.
          @@ -49,7 +48,7 @@ public Object visit(ASTPrimaryExpression node, Object data) {
           
               private void checkType(AbstractJavaTypeNode node, Object data) {
                   if (node.getType() == Timer.class) {
          -            addViolationWithMessage(data, node,"java.concurrent.AvoidUseTimerRule.violation.msg");
          +            addViolationWithMessage(data, node, "java.concurrent.AvoidUseTimerRule.violation.msg");
                   }
               }
           }
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/CountDownShouldInFinallyRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/CountDownShouldInFinallyRule.java
          similarity index 87%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/CountDownShouldInFinallyRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/CountDownShouldInFinallyRule.java
          index 022e1ab62..2b8d7a787 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/CountDownShouldInFinallyRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/CountDownShouldInFinallyRule.java
          @@ -13,18 +13,17 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.concurrent;
          -
          -import java.util.List;
          -import java.util.concurrent.CountDownLatch;
          -
          -import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule;
          +package com.xenoamess.p3c.pmd.lang.java.rule.concurrent;
           
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
           import net.sourceforge.pmd.lang.ast.Node;
           import net.sourceforge.pmd.lang.java.ast.ASTName;
           import net.sourceforge.pmd.lang.java.ast.ASTTryStatement;
           import org.jaxen.JaxenException;
           
          +import java.util.List;
          +import java.util.concurrent.CountDownLatch;
          +
           /**
            * [Recommended] When using CountDownLatch to convert asynchronous operations to synchronous ones,
            * each thread must call countdown method before quitting.
          @@ -38,7 +37,7 @@
            */
           public class CountDownShouldInFinallyRule extends AbstractAliRule {
               private static final String XPATH = "./Block/BlockStatement/Statement/StatementExpression"
          -        + "/PrimaryExpression/PrimaryPrefix/Name[ends-with(@Image,'.countDown')]";
          +            + "/PrimaryExpression/PrimaryPrefix/Name[ends-with(@Image,'.countDown')]";
           
               @Override
               public Object visit(ASTTryStatement node, Object data) {
          @@ -51,12 +50,12 @@ public Object visit(ASTTryStatement node, Object data) {
                           if (!(nameNode instanceof ASTName)) {
                               continue;
                           }
          -                ASTName name = (ASTName)nameNode;
          +                ASTName name = (ASTName) nameNode;
                           if (name.getType() != CountDownLatch.class) {
                               continue;
                           }
                           addViolationWithMessage(data, name, "java.concurrent.CountDownShouldInFinallyRule.violation.msg",
          -                    new Object[] {name.getImage()});
          +                        new Object[]{name.getImage()});
                       }
                   } catch (JaxenException ignore) {
                   }
          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/xenoamess/p3c/pmd/lang/java/rule/concurrent/ThreadLocalShouldRemoveRule.java
          similarity index 79%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/ThreadLocalShouldRemoveRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/ThreadLocalShouldRemoveRule.java
          index c2c48c4ef..bd98218e3 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/ThreadLocalShouldRemoveRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/ThreadLocalShouldRemoveRule.java
          @@ -13,16 +13,13 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.concurrent;
          -
          -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;
          +package com.xenoamess.p3c.pmd.lang.java.rule.concurrent;
           
          +import com.xenoamess.p3c.pmd.I18nResources;
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
          +import com.xenoamess.p3c.pmd.lang.java.rule.util.NodeUtils;
          +import com.xenoamess.p3c.pmd.lang.java.util.VariableUtils;
          +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils;
           import net.sourceforge.pmd.lang.ast.Node;
           import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
           import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration;
          @@ -31,6 +28,8 @@
           import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclarator;
           import org.jaxen.JaxenException;
           
          +import java.util.List;
          +
           /**
            * [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
          @@ -41,7 +40,7 @@
            */
           public class ThreadLocalShouldRemoveRule extends AbstractAliRule {
               private static final String XPATH_TPL = "//StatementExpression/PrimaryExpression"
          -        + "/PrimaryPrefix/Name[@Image='%s.remove']";
          +            + "/PrimaryPrefix/Name[@Image='%s.remove']";
           
               private static final String METHOD_INITIAL_VALUE = "initialValue";
           
          @@ -55,22 +54,24 @@ public Object visit(ASTCompilationUnit node, Object data) {
                   }
                   for (ASTFieldDeclaration fieldDeclaration : fieldDeclarations) {
                       if (NodeUtils.getNodeType(fieldDeclaration) == ThreadLocal.class) {
          -                if (checkThreadLocalWithInitalValue(fieldDeclaration)) { continue; }
          +                if (checkThreadLocalWithInitialValue(fieldDeclaration)) {
          +                    continue;
          +                }
                           checkThreadLocal(fieldDeclaration, node, data);
                       }
                   }
                   return super.visit(node, data);
               }
           
          -    private boolean checkThreadLocalWithInitalValue(ASTFieldDeclaration fieldDeclaration) {
          +    private boolean checkThreadLocalWithInitialValue(ASTFieldDeclaration fieldDeclaration) {
                   ASTVariableDeclarator variableDeclarator = fieldDeclaration.getFirstDescendantOfType(
          -            ASTVariableDeclarator.class);
          +                ASTVariableDeclarator.class);
                   if (variableDeclarator == null) {
                       return false;
                   }
                   // ASTClassOrInterfaceBodyDeclaration.isFindBoundary=true,使用getFirstDescendantOfType不能继续向方法内部查询
                   List astMethodDeclaratorList = variableDeclarator.findDescendantsOfType(
          -            ASTMethodDeclarator.class, true);
          +                ASTMethodDeclarator.class, true);
                   if (!astMethodDeclaratorList.isEmpty()) {
                       return METHOD_INITIAL_VALUE.equals(astMethodDeclaratorList.get(0).getImage());
                   }
          @@ -82,11 +83,11 @@ private void checkThreadLocal(ASTFieldDeclaration fieldDeclaration, ASTCompilati
                   try {
                       String variableName = VariableUtils.getVariableName(fieldDeclaration);
                       List nodes = node.findChildNodesWithXPath(String.format(XPATH_TPL,
          -                variableName));
          +                    variableName));
                       if (nodes == null || nodes.isEmpty()) {
                           ViolationUtils.addViolationWithPrecisePosition(this, fieldDeclaration, data,
          -                    I18nResources.getMessage("java.concurrent.ThreadLocalShouldRemoveRule.violation.msg",
          -                        variableName));
          +                        I18nResources.getMessage("java.concurrent.ThreadLocalShouldRemoveRule.violation.msg",
          +                                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/xenoamess/p3c/pmd/lang/java/rule/concurrent/ThreadPoolCreationRule.java
          similarity index 88%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/ThreadPoolCreationRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/ThreadPoolCreationRule.java
          index 4e5720920..8da07ad42 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/ThreadPoolCreationRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/ThreadPoolCreationRule.java
          @@ -13,21 +13,20 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.concurrent;
          -
          -import java.util.HashSet;
          -import java.util.List;
          -import java.util.Set;
          -import java.util.concurrent.Executors;
          -
          -import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule;
          +package com.xenoamess.p3c.pmd.lang.java.rule.concurrent;
           
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
           import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
           import net.sourceforge.pmd.lang.java.ast.ASTImportDeclaration;
           import net.sourceforge.pmd.lang.java.ast.ASTName;
           import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression;
           import net.sourceforge.pmd.lang.java.ast.Token;
           
          +import java.util.HashSet;
          +import java.util.List;
          +import java.util.Set;
          +import java.util.concurrent.Executors;
          +
           /**
            * [Mandatory] A thread pool should be created by ThreadPoolExecutor rather than Executors.
            * These would make the parameters of the thread pool understandable.
          @@ -56,20 +55,21 @@ public Object visit(ASTCompilationUnit node, Object data) {
                   for (ASTImportDeclaration importDeclaration : importDeclarations) {
                       ASTName name = importDeclaration.getFirstChildOfType(ASTName.class);
                       info.executorsUsed = info.executorsUsed
          -                || (name.getType() == Executors.class || Executors.class.getName().equals(name.getImage()));
          +                    || (name.getType() == Executors.class || Executors.class.getName().equals(name.getImage()));
                       if (name.getImage().startsWith(Executors.class.getName() + DOT)) {
                           info.importedExecutorsMethods.add(name.getImage());
                       }
                   }
                   List primaryExpressions = node.findDescendantsOfType(ASTPrimaryExpression.class);
          -        for(ASTPrimaryExpression primaryExpression : primaryExpressions){
          +        for (ASTPrimaryExpression primaryExpression : primaryExpressions) {
                       if (!info.executorsUsed && info.importedExecutorsMethods.isEmpty()) {
                           continue;
                       }
           
          -            Token initToken = (Token)primaryExpression.jjtGetFirstToken();
          +            Token initToken = (Token) primaryExpression.jjtGetFirstToken();
                       if (!checkInitStatement(initToken, info)) {
          -                addViolationWithMessage(data, primaryExpression,"java.concurrent.ThreadPoolCreationRule.violation.msg");
          +                addViolationWithMessage(data, primaryExpression, "java.concurrent.ThreadPoolCreationRule.violation" +
          +                        ".msg");
                       }
                   }
                   return superResult;
          @@ -114,8 +114,8 @@ private String getFullAssignStatement(final Token token) {
                   return sb.toString();
               }
           
          -    class Info {
          +    static class Info {
                   boolean executorsUsed;
          -        Set importedExecutorsMethods = new HashSet<>();
          +        final Set importedExecutorsMethods = new HashSet<>();
               }
           }
          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/xenoamess/p3c/pmd/lang/java/rule/concurrent/ThreadShouldSetNameRule.java
          similarity index 85%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/ThreadShouldSetNameRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/ThreadShouldSetNameRule.java
          index efbe4c563..6a819aa1c 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/ThreadShouldSetNameRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/ThreadShouldSetNameRule.java
          @@ -13,18 +13,9 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.concurrent;
          -
          -import java.util.List;
          -import java.util.concurrent.ExecutorService;
          -import java.util.concurrent.Executors;
          -import java.util.concurrent.RejectedExecutionHandler;
          -import java.util.concurrent.ScheduledThreadPoolExecutor;
          -import java.util.concurrent.ThreadFactory;
          -import java.util.concurrent.ThreadPoolExecutor;
          -
          -import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule;
          +package com.xenoamess.p3c.pmd.lang.java.rule.concurrent;
           
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
           import net.sourceforge.pmd.lang.java.ast.ASTAllocationExpression;
           import net.sourceforge.pmd.lang.java.ast.ASTArgumentList;
           import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
          @@ -35,6 +26,14 @@
           import net.sourceforge.pmd.lang.java.ast.ASTName;
           import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
           
          +import java.util.List;
          +import java.util.concurrent.ExecutorService;
          +import java.util.concurrent.Executors;
          +import java.util.concurrent.RejectedExecutionHandler;
          +import java.util.concurrent.ScheduledThreadPoolExecutor;
          +import java.util.concurrent.ThreadFactory;
          +import java.util.concurrent.ThreadPoolExecutor;
          +
           /**
            * [Mandatory] A meaningful thread name is helpful to trace the error information,
            * so assign a name when creating threads or thread pools.
          @@ -80,11 +79,11 @@ public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
           
               private Object checkThreadPoolExecutor(ASTAllocationExpression node, Object data) {
                   ASTArgumentList argumentList = node.getFirstDescendantOfType(ASTArgumentList.class);
          -        if (argumentList.jjtGetNumChildren() > ARGUMENT_LENGTH_6) {
          +        if (argumentList.getNumChildren() > ARGUMENT_LENGTH_6) {
                       return true;
                   }
          -        if (argumentList.jjtGetNumChildren() < ARGUMENT_LENGTH_6
          -            || !checkThreadFactoryArgument((ASTExpression)argumentList.jjtGetChild(ARGUMENT_LENGTH_6 - INDEX_1))) {
          +        if (argumentList.getNumChildren() < ARGUMENT_LENGTH_6
          +                || !checkThreadFactoryArgument((ASTExpression) argumentList.getChild(ARGUMENT_LENGTH_6 - INDEX_1))) {
                       addViolationWithMessage(data, node, MESSAGE_KEY_PREFIX + ".ThreadPoolExecutor");
                   }
                   return super.visit(node, data);
          @@ -92,16 +91,17 @@ private Object checkThreadPoolExecutor(ASTAllocationExpression node, Object data
           
               private Object checkSchedulePoolExecutor(ASTAllocationExpression node, Object data) {
                   ASTArgumentList argumentList = node.getFirstDescendantOfType(ASTArgumentList.class);
          -        if (argumentList.jjtGetNumChildren() > ARGUMENT_LENGTH_2) {
          +        if (argumentList.getNumChildren() > ARGUMENT_LENGTH_2) {
                       return true;
                   }
          -        if (argumentList.jjtGetNumChildren() < ARGUMENT_LENGTH_2
          -            || !checkThreadFactoryArgument((ASTExpression)argumentList.jjtGetChild(ARGUMENT_LENGTH_2 - INDEX_1))) {
          +        if (argumentList.getNumChildren() < ARGUMENT_LENGTH_2
          +                || !checkThreadFactoryArgument((ASTExpression) argumentList.getChild(ARGUMENT_LENGTH_2 - INDEX_1))) {
                       addViolationWithMessage(data, node, MESSAGE_KEY_PREFIX + ".ScheduledThreadPoolExecutor");
                   }
                   return super.visit(node, data);
               }
           
          +    @SuppressWarnings("BooleanMethodIsAlwaysInverted")
               private boolean checkThreadFactoryArgument(ASTExpression expression) {
                   if (expression.getType() != null && ThreadFactory.class.isAssignableFrom(expression.getType())) {
                       return true;
          @@ -113,16 +113,15 @@ private boolean checkThreadFactoryArgument(ASTExpression expression) {
                   ASTLambdaExpression lambdaExpression = expression.getFirstDescendantOfType(ASTLambdaExpression.class);
                   if (lambdaExpression != null) {
                       return isThreadFactoryLambda(lambdaExpression);
          -        } else if (expression.getType() != null
          -            && RejectedExecutionHandler.class.isAssignableFrom(expression.getType())) {
          -            return false;
          +        } else {
          +            return expression.getType() == null
          +                    || !RejectedExecutionHandler.class.isAssignableFrom(expression.getType());
                   }
          -        return true;
               }
           
               private boolean isThreadFactoryLambda(ASTLambdaExpression lambdaExpression) {
                   List variableDeclaratorIds =
          -            lambdaExpression.findChildrenOfType(ASTVariableDeclaratorId.class);
          +                lambdaExpression.findChildrenOfType(ASTVariableDeclaratorId.class);
                   if (variableDeclaratorIds != null && !variableDeclaratorIds.isEmpty()) {
                       return variableDeclaratorIds.size() == SINGLE_LENGTH;
                   }
          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/xenoamess/p3c/pmd/lang/java/rule/constant/UndefineMagicConstantRule.java
          similarity index 81%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/constant/UndefineMagicConstantRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/constant/UndefineMagicConstantRule.java
          index 70a387541..5f9293103 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/constant/UndefineMagicConstantRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/constant/UndefineMagicConstantRule.java
          @@ -13,25 +13,22 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.constant;
          -
          -import java.util.ArrayList;
          -import java.util.List;
          -
          -import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule;
          -import com.alibaba.p3c.pmd.lang.java.util.namelist.NameListConfig;
          +package com.xenoamess.p3c.pmd.lang.java.rule.constant;
           
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.namelist.NameListConfig;
           import net.sourceforge.pmd.lang.ast.Node;
           import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
           import net.sourceforge.pmd.lang.java.ast.ASTForStatement;
           import net.sourceforge.pmd.lang.java.ast.ASTIfStatement;
           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;
           
          +import java.util.ArrayList;
          +import java.util.List;
          +
           /**
            * [Mandatory] Magic values, except for predefined, are forbidden in coding.
            *
          @@ -42,11 +39,16 @@ public class UndefineMagicConstantRule extends AbstractAliRule {
           
               /**
                * white list for undefined variable, may be added
          +     * @return UndefineMagicConstantRule LITERAL_WHITE_LIST
                */
          -    private final static List LITERAL_WHITE_LIST = NameListConfig.NAME_LIST_SERVICE.getNameList(
          -        UndefineMagicConstantRule.class.getSimpleName(), "LITERAL_WHITE_LIST");
          +    private static List getLiteralWhiteList() {
          +        return NameListConfig.getNameListService().getNameList(
          +                UndefineMagicConstantRule.class.getSimpleName(),
          +                "LITERAL_WHITE_LIST"
          +        );
          +    }
           
          -    private final static String XPATH = "//Literal/../../../../..[not(VariableInitializer)]";
          +    private static final String XPATH = "//Literal/../../../../..[not(VariableInitializer)]";
           
               /**
                * An undefined that belongs to non-looped if statements
          @@ -57,7 +59,7 @@ public class UndefineMagicConstantRule extends AbstractAliRule {
               @Override
               public Object visit(ASTCompilationUnit node, Object data) {
                   // removed repeat magic value , to prevent the parent class to find sub-variable nodes when there is a repeat
          -        List currentLiterals = new ArrayList();
          +        List currentLiterals = new ArrayList<>();
                   try {
                       // Find the parent node of the undefined variable
                       List parentNodes = node.findChildNodesWithXPath(XPATH);
          @@ -69,7 +71,7 @@ public Object visit(ASTCompilationUnit node, Object data) {
                                   currentLiterals.add(literal);
                                   String imageReplace = StringUtils.replace(literal.getImage(), "{", "'{");
                                   addViolationWithMessage(data, literal,
          -                            "java.constant.UndefineMagicConstantRule.violation.msg", new Object[] {imageReplace});
          +                                "java.constant.UndefineMagicConstantRule.violation.msg", new Object[]{imageReplace});
                               }
                           }
                       }
          @@ -82,8 +84,8 @@ public Object visit(ASTCompilationUnit node, Object data) {
               /**
                * Undefined variables are in the blacklist
                *
          -     * @param literal
          -     * @return
          +     * @param literal literal
          +     * @return ifInBlackList
                */
               private boolean inBlackList(ASTLiteral literal) {
                   String name = literal.getImage();
          @@ -93,7 +95,7 @@ private boolean inBlackList(ASTLiteral literal) {
                       return false;
                   }
                   // filter white list
          -        for (String whiteItem : LITERAL_WHITE_LIST) {
          +        for (String whiteItem : getLiteralWhiteList()) {
                       if (whiteItem.equals(name)) {
                           return false;
                       }
          @@ -105,7 +107,7 @@ private boolean inBlackList(ASTLiteral literal) {
                       return forStatement == null && whileStatement == null;
                   }
           
          -        // judge magic value belongs to  for statement 
          +        // judge magic value belongs to  for statement
                   ASTForStatement blackForStatement = literal.getFirstParentOfType(ASTForStatement.class);
                   if (blackForStatement != null && lineNum == blackForStatement.getBeginLine()) {
                       return true;
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/constant/UpperEllRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/constant/UpperEllRule.java
          similarity index 89%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/constant/UpperEllRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/constant/UpperEllRule.java
          index a5178bbda..13624fdac 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/constant/UpperEllRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/constant/UpperEllRule.java
          @@ -13,10 +13,9 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.constant;
          -
          -import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule;
          +package com.xenoamess.p3c.pmd.lang.java.rule.constant;
           
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
           import net.sourceforge.pmd.lang.java.ast.ASTLiteral;
           
           /**
          @@ -35,7 +34,7 @@ public Object visit(ASTLiteral node, Object data) {
                   // if it is an integer and ends with l, collects the current violation code
                   if (image != null && node.isLongLiteral() && image.endsWith(LOWERCASE_L)) {
                       addViolationWithMessage(data, node, "java.constant.UpperEllRule.violation.msg",
          -                new Object[] {node.getImage()});
          +                    new Object[]{node.getImage()});
                   }
                   return super.visit(node, data);
               }
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/exception/AvoidReturnInFinallyRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/exception/AvoidReturnInFinallyRule.java
          similarity index 75%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/exception/AvoidReturnInFinallyRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/exception/AvoidReturnInFinallyRule.java
          index 5ade344cd..38484486c 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/exception/AvoidReturnInFinallyRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/exception/AvoidReturnInFinallyRule.java
          @@ -13,23 +13,22 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.exception;
          -
          -import com.alibaba.p3c.pmd.I18nResources;
          -import com.alibaba.p3c.pmd.lang.AbstractXpathRule;
          -import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils;
          +package com.xenoamess.p3c.pmd.lang.java.rule.exception;
           
          +import com.xenoamess.p3c.pmd.I18nResources;
          +import com.xenoamess.p3c.pmd.lang.AbstractAliXpathRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils;
           import net.sourceforge.pmd.lang.ast.Node;
           
           /**
            * [Mandatory] Never use return within a finally block.
            * A return statement in a finally block will cause exception or result
            * in a discarded return value in the try-catch block.
          - * 
          + *
            * @author zenghou.fw
            * @date 2017/03/29
            */
          -public class AvoidReturnInFinallyRule extends AbstractXpathRule {
          +public class AvoidReturnInFinallyRule extends AbstractAliXpathRule {
               private static final String XPATH = "//FinallyStatement//ReturnStatement";
           
               public AvoidReturnInFinallyRule() {
          @@ -39,6 +38,6 @@ public AvoidReturnInFinallyRule() {
               @Override
               public void addViolation(Object data, Node node, String arg) {
                   ViolationUtils.addViolationWithPrecisePosition(this, node, data,
          -            I18nResources.getMessage("java.exception.AvoidReturnInFinallyRule.violation.msg"));
          +                I18nResources.getMessage("java.exception.AvoidReturnInFinallyRule.violation.msg"));
               }
           }
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/exception/MethodReturnWrapperTypeRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/exception/MethodReturnWrapperTypeRule.java
          similarity index 70%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/exception/MethodReturnWrapperTypeRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/exception/MethodReturnWrapperTypeRule.java
          index e84c1a486..c2014cb3f 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/exception/MethodReturnWrapperTypeRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/exception/MethodReturnWrapperTypeRule.java
          @@ -13,16 +13,12 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.exception;
          -
          -import java.util.List;
          -import java.util.Map;
          -
          -import com.alibaba.p3c.pmd.I18nResources;
          -import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule;
          -import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils;
          -import com.alibaba.p3c.pmd.lang.java.util.namelist.NameListConfig;
          +package com.xenoamess.p3c.pmd.lang.java.rule.exception;
           
          +import com.xenoamess.p3c.pmd.I18nResources;
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils;
          +import com.xenoamess.p3c.pmd.lang.java.util.namelist.NameListConfig;
           import net.sourceforge.pmd.lang.ast.Node;
           import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType;
           import net.sourceforge.pmd.lang.java.ast.ASTLocalVariableDeclaration;
          @@ -32,6 +28,9 @@
           import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
           import org.jaxen.JaxenException;
           
          +import java.util.List;
          +import java.util.Map;
          +
           /**
            * [Recommended] If the return type is primitive, return a value of wrapper class may cause NullPointerException.
            *
          @@ -39,14 +38,19 @@
            * @date 2017/04/16
            */
           public class MethodReturnWrapperTypeRule extends AbstractAliRule {
          -    private static final Map PRIMITIVE_TYPE_TO_WAPPER_TYPE = NameListConfig.NAME_LIST_SERVICE
          -        .getNameMap("MethodReturnWrapperTypeRule", "PRIMITIVE_TYPE_TO_WAPPER_TYPE", String.class, String.class);
          +    private static Map getPrimitiveTypeToWrapperType() {
          +        return NameListConfig.getNameListService().getNameMap(
          +                "MethodReturnWrapperTypeRule",
          +                "PRIMITIVE_TYPE_TO_WRAPPER_TYPE"
          +        );
          +    }
          +
               private static final String METHOD_RETURN_TYPE_XPATH = "ResultType/Type/PrimitiveType";
               private static final String METHOD_RETURN_OBJECT_XPATH
          -        = "Block/BlockStatement/Statement/ReturnStatement/Expression/PrimaryExpression/PrimaryPrefix/Name";
          +            = "Block/BlockStatement/Statement/ReturnStatement/Expression/PrimaryExpression/PrimaryPrefix/Name";
               private static final String METHOD_VARIABLE_TYPE_XPATH = "Type/ReferenceType/ClassOrInterfaceType";
               private static final String METHOD_VARIABLE_NAME_XPATH
          -        = "Block/BlockStatement/LocalVariableDeclaration/VariableDeclarator/VariableDeclaratorId";
          +            = "Block/BlockStatement/LocalVariableDeclaration/VariableDeclarator/VariableDeclaratorId";
           
               @Override
               public Object visit(ASTMethodDeclaration node, Object data) {
          @@ -56,7 +60,7 @@ public Object visit(ASTMethodDeclaration node, Object data) {
                       if (!(astPrimitiveTypeList != null && astPrimitiveTypeList.size() == 1)) {
                           return super.visit(node, data);
                       }
          -            ASTPrimitiveType astPrimitiveType = (ASTPrimitiveType)astPrimitiveTypeList.get(0);
          +            ASTPrimitiveType astPrimitiveType = (ASTPrimitiveType) astPrimitiveTypeList.get(0);
                       //If the return type is not a basic types,skip
                       if (!(astPrimitiveType.getType() != null && astPrimitiveType.getType().isPrimitive())) {
                           return super.visit(node, data);
          @@ -73,32 +77,33 @@ public Object visit(ASTMethodDeclaration node, Object data) {
                       if (methodVariableNameList == null || methodVariableNameList.size() == 0) {
                           return super.visit(node, data);
                       }
          -            ASTName astName = (ASTName)nameList.get(0);
          +            ASTName astName = (ASTName) nameList.get(0);
                       String variableName = astName.getImage();
                       //iterate all the method of variable nodes
                       for (Node methodVariableNameNode : methodVariableNameList) {
                           ASTVariableDeclaratorId astVariableDeclaratorId
          -                    = (ASTVariableDeclaratorId)methodVariableNameNode;
          +                        = (ASTVariableDeclaratorId) methodVariableNameNode;
                           //find out the variable named the same with return node
                           if (!variableName.equals(astVariableDeclaratorId.getImage())) {
                               continue;
                           }
                           ASTLocalVariableDeclaration astLocalVariableDeclaration = astVariableDeclaratorId
          -                    .getFirstParentOfType(ASTLocalVariableDeclaration.class);
          +                        .getFirstParentOfType(ASTLocalVariableDeclaration.class);
                           //check local variables type
                           List nodeList = astLocalVariableDeclaration.findChildNodesWithXPath(
          -                    METHOD_VARIABLE_TYPE_XPATH);
          +                        METHOD_VARIABLE_TYPE_XPATH);
           
                           if (nodeList != null && nodeList.size() == 1) {
          -                    ASTClassOrInterfaceType astClassOrInterfaceType = (ASTClassOrInterfaceType)nodeList.get(
          -                        0);
          +                    ASTClassOrInterfaceType astClassOrInterfaceType = (ASTClassOrInterfaceType) nodeList.get(
          +                            0);
          +                    Map primitiveTypeToWrapperType = getPrimitiveTypeToWrapperType();
                               //if variable type is a value of wrapper
          -                    if (PRIMITIVE_TYPE_TO_WAPPER_TYPE.get(primitiveTypeName) != null
          -                        && PRIMITIVE_TYPE_TO_WAPPER_TYPE.get(primitiveTypeName).equals(
          -                        astClassOrInterfaceType.getType().getSimpleName())) {
          +                    if (primitiveTypeToWrapperType.get(primitiveTypeName) != null
          +                            && primitiveTypeToWrapperType.get(primitiveTypeName).equals(
          +                            astClassOrInterfaceType.getType().getSimpleName())) {
                                   ViolationUtils.addViolationWithPrecisePosition(this, node, data,
          -                            I18nResources.getMessage("java.exception.MethodReturnWrapperTypeRule.violation.msg",
          -                                primitiveTypeName, astClassOrInterfaceType.getType().getSimpleName()));
          +                                I18nResources.getMessage("java.exception.MethodReturnWrapperTypeRule.violation.msg",
          +                                        primitiveTypeName, astClassOrInterfaceType.getType().getSimpleName()));
                               }
                           }
                       }
          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/xenoamess/p3c/pmd/lang/java/rule/exception/TransactionMustHaveRollbackRule.java
          similarity index 88%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/exception/TransactionMustHaveRollbackRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/exception/TransactionMustHaveRollbackRule.java
          index 583a11976..1dda53b25 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/exception/TransactionMustHaveRollbackRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/exception/TransactionMustHaveRollbackRule.java
          @@ -13,12 +13,9 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.exception;
          -
          -import java.util.List;
          -
          -import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule;
          +package com.xenoamess.p3c.pmd.lang.java.rule.exception;
           
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
           import net.sourceforge.pmd.lang.ast.Node;
           import net.sourceforge.pmd.lang.java.ast.ASTAnnotation;
           import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
          @@ -27,6 +24,8 @@
           import net.sourceforge.pmd.lang.java.ast.ASTName;
           import org.jaxen.JaxenException;
           
          +import java.util.List;
          +
           /**
            * [Mandatory] Make sure to invoke the rollback if a method throws an Exception.
            *
          @@ -36,7 +35,7 @@
           public class TransactionMustHaveRollbackRule extends AbstractAliRule {
               private static final String TRANSACTIONAL_ANNOTATION_NAME = "Transactional";
               private static final String TRANSACTIONAL_FULL_NAME = "org.springframework.transaction.annotation."
          -        + TRANSACTIONAL_ANNOTATION_NAME;
          +            + TRANSACTIONAL_ANNOTATION_NAME;
               private static final String ROLLBACK_PREFIX = "rollback";
           
               private static final String READ_ONLY = "readOnly";
          @@ -44,7 +43,7 @@ public class TransactionMustHaveRollbackRule extends AbstractAliRule {
               private static final String PROPAGATION_NOT_SUPPORTED = "Propagation.NOT_SUPPORTED";
           
               private static final String XPATH_FOR_ROLLBACK = "//StatementExpression/PrimaryExpression"
          -        + "/PrimaryPrefix/Name[ends-with(@Image,'rollback')]";
          +            + "/PrimaryPrefix/Name[ends-with(@Image,'rollback')]";
           
               private static final String MESSAGE_KEY_PREFIX = "java.exception.TransactionMustHaveRollbackRule.violation.msg";
           
          @@ -52,7 +51,7 @@ public class TransactionMustHaveRollbackRule extends AbstractAliRule {
               public Object visit(ASTAnnotation node, Object data) {
                   ASTName name = node.getFirstDescendantOfType(ASTName.class);
                   boolean noTransactional = name == null || !(TRANSACTIONAL_ANNOTATION_NAME.equals(name.getImage())
          -            && !TRANSACTIONAL_FULL_NAME.equals(name.getImage()));
          +                && !TRANSACTIONAL_FULL_NAME.equals(name.getImage()));
                   if (noTransactional) {
                       return super.visit(node, data);
                   }
          @@ -62,7 +61,7 @@ public Object visit(ASTAnnotation node, Object data) {
                   }
           
                   ASTClassOrInterfaceDeclaration classOrInterfaceDeclaration
          -            = getSiblingForType(node, ASTClassOrInterfaceDeclaration.class);
          +                = getSiblingForType(node, ASTClassOrInterfaceDeclaration.class);
                   if (classOrInterfaceDeclaration != null) {
                       addViolationWithMessage(data, node, MESSAGE_KEY_PREFIX + ".simple");
                       return super.visit(node, data);
          @@ -78,7 +77,7 @@ public Object visit(ASTAnnotation node, Object data) {
                           return super.visit(node, data);
                       }
                       addViolationWithMessage(data, methodDeclaration, MESSAGE_KEY_PREFIX,
          -                new Object[] {methodDeclaration.getMethodName()});
          +                    new Object[]{methodDeclaration.getName()});
                   } catch (JaxenException ignore) {
                   }
                   return super.visit(node, data);
          @@ -110,10 +109,10 @@ private boolean shouldSkip(List memberValuePairList) {
                * @return sibling node
                */
               private  T getSiblingForType(ASTAnnotation node, Class clz) {
          -        Node parent = node.jjtGetParent();
          -        int num = parent.jjtGetNumChildren();
          +        Node parent = node.getParent();
          +        int num = parent.getNumChildren();
                   for (int i = 0; i < num; i++) {
          -            Node child = parent.jjtGetChild(i);
          +            Node child = parent.getChild(i);
                       if (clz.isAssignableFrom(child.getClass())) {
                           return clz.cast(child);
                       }
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/AvoidComplexConditionRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/flowcontrol/AvoidComplexConditionRule.java
          similarity index 72%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/AvoidComplexConditionRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/flowcontrol/AvoidComplexConditionRule.java
          index e97b649bc..57bb44ee2 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/AvoidComplexConditionRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/flowcontrol/AvoidComplexConditionRule.java
          @@ -13,11 +13,10 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.flowcontrol;
          -
          -import com.alibaba.p3c.pmd.lang.AbstractXpathRule;
          -import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils;
          +package com.xenoamess.p3c.pmd.lang.java.rule.flowcontrol;
           
          +import com.xenoamess.p3c.pmd.lang.AbstractAliXpathRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils;
           import net.sourceforge.pmd.lang.ast.Node;
           
           /**
          @@ -28,10 +27,10 @@
            * @author zenghou.fw
            * @date 2017/04/11
            */
          -public class AvoidComplexConditionRule extends AbstractXpathRule {
          +public class AvoidComplexConditionRule extends AbstractAliXpathRule {
               private static final String XPATH = "(//IfStatement/Expression"
          -        + "|//ConditionalExpression[@Ternary = 'true']/PrimaryExpression)"
          -        + "[count(.//ConditionalAndExpression) + count(.//ConditionalOrExpression) > 1]";
          +            + "|//ConditionalExpression/PrimaryExpression)"
          +            + "[count(.//ConditionalAndExpression) + count(.//ConditionalOrExpression) > 1]";
           
               public AvoidComplexConditionRule() {
                   setXPath(XPATH);
          @@ -40,6 +39,6 @@ public AvoidComplexConditionRule() {
               @Override
               public void addViolation(Object data, Node node, String arg) {
                   ViolationUtils.addViolationWithPrecisePosition(this, node, data,
          -            "java.flowcontrol.AvoidComplexConditionRule.violation.msg");
          +                "java.flowcontrol.AvoidComplexConditionRule.violation.msg");
               }
           }
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/AvoidNegationOperatorRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/flowcontrol/AvoidNegationOperatorRule.java
          similarity index 70%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/AvoidNegationOperatorRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/flowcontrol/AvoidNegationOperatorRule.java
          index 0ee5621aa..a7601b0d8 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/AvoidNegationOperatorRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/flowcontrol/AvoidNegationOperatorRule.java
          @@ -13,11 +13,10 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.flowcontrol;
          -
          -import com.alibaba.p3c.pmd.lang.AbstractXpathRule;
          -import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils;
          +package com.xenoamess.p3c.pmd.lang.java.rule.flowcontrol;
           
          +import com.xenoamess.p3c.pmd.lang.AbstractAliXpathRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils;
           import net.sourceforge.pmd.lang.ast.Node;
           
           /**
          @@ -28,11 +27,11 @@
            * @author zenghou.fw
            * @date 2017/11/21
            */
          -public class AvoidNegationOperatorRule extends AbstractXpathRule {
          +public class AvoidNegationOperatorRule extends AbstractAliXpathRule {
               private static final String XPATH = "//UnaryExpressionNotPlusMinus[child::PrimaryExpression"
          -        + "//PrimaryPrefix/Expression/RelationalExpression]"
          -        + "|//UnaryExpressionNotPlusMinus[child::PrimaryExpression"
          -        + "//PrimaryPrefix/Expression/EqualityExpression]";
          +            + "//PrimaryPrefix/Expression/RelationalExpression]"
          +            + "|//UnaryExpressionNotPlusMinus[child::PrimaryExpression"
          +            + "//PrimaryPrefix/Expression/EqualityExpression]";
           
               public AvoidNegationOperatorRule() {
                   setXPath(XPATH);
          @@ -41,6 +40,6 @@ public AvoidNegationOperatorRule() {
               @Override
               public void addViolation(Object data, Node node, String arg) {
                   ViolationUtils.addViolationWithPrecisePosition(this, node, data,
          -            "java.flowcontrol.AvoidNegationOperatorRule.violation.msg");
          +                "java.flowcontrol.AvoidNegationOperatorRule.violation.msg");
               }
           }
          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/xenoamess/p3c/pmd/lang/java/rule/flowcontrol/NeedBraceRule.java
          similarity index 88%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/NeedBraceRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/flowcontrol/NeedBraceRule.java
          index 20ca6d3c9..a6ce2b0e0 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/NeedBraceRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/flowcontrol/NeedBraceRule.java
          @@ -13,10 +13,9 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.flowcontrol;
          -
          -import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule;
          +package com.xenoamess.p3c.pmd.lang.java.rule.flowcontrol;
           
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
           import net.sourceforge.pmd.lang.java.ast.ASTBlock;
           import net.sourceforge.pmd.lang.java.ast.ASTForStatement;
           import net.sourceforge.pmd.lang.java.ast.ASTIfStatement;
          @@ -40,17 +39,17 @@ public class NeedBraceRule extends AbstractAliRule {
           
               @Override
               public Object visit(ASTIfStatement node, Object data) {
          -        // SwitchStatement without {} fail by compilaton, no need to check here
          +        // SwitchStatement without {} fail by compilation, no need to check here
                   if (!node.hasDescendantMatchingXPath(STATEMENT_BLOCK)) {
                       addViolationWithMessage(data, node, MESSAGE_KEY,
          -                new Object[] {node.jjtGetFirstToken().toString()});
          +                    new Object[]{node.jjtGetFirstToken().toString()});
                   }
                   if (node.hasElse()) {
                       // IfStatement with else have 2 expression blocks, should never throws NPE
                       ASTStatement elseStms = node.findChildrenOfType(ASTStatement.class).get(1);
           
                       if (!elseStms.hasDescendantOfAnyType(ASTBlock.class, ASTIfStatement.class)) {
          -                addViolationWithMessage(data, elseStms, MESSAGE_KEY, new Object[] {"else"});
          +                addViolationWithMessage(data, elseStms, MESSAGE_KEY, new Object[]{"else"});
                       }
                   }
                   return super.visit(node, data);
          @@ -59,7 +58,7 @@ public Object visit(ASTIfStatement node, Object data) {
               @Override
               public Object visit(ASTForStatement node, Object data) {
                   if (!node.hasDescendantMatchingXPath(STATEMENT_BLOCK)) {
          -            addViolationWithMessage(data, node, MESSAGE_KEY, new Object[] {"for"});
          +            addViolationWithMessage(data, node, MESSAGE_KEY, new Object[]{"for"});
                   }
                   return super.visit(node, data);
               }
          @@ -67,7 +66,7 @@ public Object visit(ASTForStatement node, Object data) {
               @Override
               public Object visit(ASTWhileStatement node, Object data) {
                   if (!node.hasDescendantMatchingXPath(STATEMENT_BLOCK)) {
          -            addViolationWithMessage(data, node, MESSAGE_KEY, new Object[] {"while"});
          +            addViolationWithMessage(data, node, MESSAGE_KEY, new Object[]{"while"});
                   }
                   return super.visit(node, data);
               }
          diff --git a/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/flowcontrol/SwitchExpressionRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/flowcontrol/SwitchExpressionRule.java
          new file mode 100644
          index 000000000..b2440b17e
          --- /dev/null
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/flowcontrol/SwitchExpressionRule.java
          @@ -0,0 +1,56 @@
          +/*
          + * 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.xenoamess.p3c.pmd.lang.java.rule.flowcontrol;
          +
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
          +import net.sourceforge.pmd.lang.java.ast.ASTSwitchExpression;
          +
          +/**
          + * [Mandatory] In a switch expression, each case should be finished by break/return.
          + * If not, a note should be included to describe at which case it will stop. Within every switch block,
          + * a default statement must be present, even if it is empty.
          + *
          + * @author XenoAmess
          + * @date 2020/4/22
          + */
          +public class SwitchExpressionRule extends AbstractAliRule {
          +    private static final String MESSAGE_KEY_PREFIX = "java.flowcontrol.SwitchExpressionRule.violation";
          +
          +    @Override
          +    public Object visit(ASTSwitchExpression node, Object data) {
          +        checkDefault(node, data);
          +        return super.visit(node, data);
          +    }
          +
          +    /**
          +     * Check if switch statement contains default branch
          +     *
          +     * @param node node
          +     * @param data ruleContext
          +     */
          +    private void checkDefault(ASTSwitchExpression node, Object data) {
          +        final String switchLabelCheckXpath = "SwitchLabel[@Default = 'true']";
          +        final String switchLabeledExpressionCheckXpath = "SwitchLabeledExpression[SwitchLabel[@Default = 'true']]";
          +        final String switchLabeledBlockCheckXpath = "SwitchLabeledBlock[SwitchLabel[@Default = 'true']]";
          +        if (
          +                !node.hasDescendantMatchingXPath(switchLabelCheckXpath)
          +                        && !node.hasDescendantMatchingXPath(switchLabeledExpressionCheckXpath)
          +                        && !node.hasDescendantMatchingXPath(switchLabeledBlockCheckXpath)
          +        ) {
          +            addViolationWithMessage(data, node, MESSAGE_KEY_PREFIX + ".nodefault");
          +        }
          +    }
          +}
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/SwitchStatementRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/flowcontrol/SwitchStatementRule.java
          similarity index 51%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/SwitchStatementRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/flowcontrol/SwitchStatementRule.java
          index c6decb5b4..76fd558ce 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/SwitchStatementRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/flowcontrol/SwitchStatementRule.java
          @@ -13,10 +13,9 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.flowcontrol;
          -
          -import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule;
          +package com.xenoamess.p3c.pmd.lang.java.rule.flowcontrol;
           
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
           import net.sourceforge.pmd.lang.java.ast.ASTSwitchStatement;
           
           /**
          @@ -42,12 +41,18 @@ public Object visit(ASTSwitchStatement node, Object data) {
               /**
                * Check if switch statement contains default branch
                *
          -     * @param node
          -     * @param data
          +     * @param node node
          +     * @param data ruleContext
                */
               private void checkDefault(ASTSwitchStatement node, Object data) {
          -        final String switchCheckXpath = "SwitchLabel[@Default = 'true']";
          -        if (!node.hasDescendantMatchingXPath(switchCheckXpath)) {
          +        final String switchLabelCheckXpath = "SwitchLabel[@Default = 'true']";
          +        final String switchLabeledExpressionCheckXpath = "SwitchLabeledExpression[SwitchLabel[@Default = 'true']]";
          +        final String switchLabeledBlockCheckXpath = "SwitchLabeledBlock[SwitchLabel[@Default = 'true']]";
          +        if (
          +                !node.hasDescendantMatchingXPath(switchLabelCheckXpath)
          +                        && !node.hasDescendantMatchingXPath(switchLabeledExpressionCheckXpath)
          +                        && !node.hasDescendantMatchingXPath(switchLabeledBlockCheckXpath)
          +        ) {
                       addViolationWithMessage(data, node, MESSAGE_KEY_PREFIX + ".nodefault");
                   }
               }
          @@ -55,25 +60,27 @@ private void checkDefault(ASTSwitchStatement node, Object data) {
               /**
                * Check the availability of break, return, throw, continue in case statement
                *
          -     * @param node
          -     * @param data
          +     * @param node node
          +     * @param data ruleContext
                */
               private void checkFallThrough(ASTSwitchStatement node, Object data) {
                   // refer the rule MissingBreakInSwitch of PMD
                   final String xpath = "../SwitchStatement[(count(.//BreakStatement)"
          -            + " + count(BlockStatement//Statement/ReturnStatement)"
          -            + " + count(BlockStatement//Statement/ContinueStatement)"
          -            + " + count(BlockStatement//Statement/ThrowStatement)"
          -            + " + count(BlockStatement//Statement/IfStatement[@Else='true'"
          -            + " and Statement[2][ReturnStatement|ContinueStatement|ThrowStatement]]"
          -            + "/Statement[1][ReturnStatement|ContinueStatement|ThrowStatement])"
          -            + " + count(SwitchLabel[name(following-sibling::node()) = 'SwitchLabel'])"
          -            + " + count(SwitchLabel[count(following-sibling::node()) = 0])"
          -            + "  < count (SwitchLabel[@Default != 'true'])"
          -            + " + count(SwitchLabel[@Default = 'true']/following-sibling::BlockStatement//Statement/ReturnStatement)"
          -            + " + count(SwitchLabel[@Default = 'true']/following-sibling::BlockStatement//Statement/ContinueStatement)"
          -            + " + count(SwitchLabel[@Default = 'true']/following-sibling::BlockStatement//Statement/ThrowStatement)"
          -            + ")]";
          +                + " + count(BlockStatement//Statement/ReturnStatement)"
          +                + " + count(BlockStatement//Statement/ContinueStatement)"
          +                + " + count(BlockStatement//Statement/ThrowStatement)"
          +                + " + count(BlockStatement//Statement/IfStatement[@Else='true'"
          +                + " and Statement[2][ReturnStatement|ContinueStatement|ThrowStatement]]"
          +                + "/Statement[1][ReturnStatement|ContinueStatement|ThrowStatement])"
          +                + " + count(SwitchLabel[name(following-sibling::node()) = 'SwitchLabel'])"
          +                + " + count(SwitchLabel[count(following-sibling::node()) = 0])"
          +                + "  < count (SwitchLabel[@Default != 'true'])"
          +                + " + count(SwitchLabel[@Default = 'true']/following-sibling::BlockStatement//Statement" +
          +                "/ReturnStatement)"
          +                + " + count(SwitchLabel[@Default = 'true']/following-sibling::BlockStatement//Statement" +
          +                "/ContinueStatement)"
          +                + " + count(SwitchLabel[@Default = 'true']/following-sibling::BlockStatement//Statement/ThrowStatement)"
          +                + ")]";
           
                   if (node.hasDescendantMatchingXPath(xpath)) {
                       addViolationWithMessage(data, node, MESSAGE_KEY_PREFIX + ".notermination");
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/AbstractClassShouldStartWithAbstractNamingRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/AbstractClassShouldStartWithAbstractNamingRule.java
          similarity index 72%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/AbstractClassShouldStartWithAbstractNamingRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/AbstractClassShouldStartWithAbstractNamingRule.java
          index a549d56c6..052539157 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/AbstractClassShouldStartWithAbstractNamingRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/AbstractClassShouldStartWithAbstractNamingRule.java
          @@ -13,12 +13,11 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.naming;
          -
          -import com.alibaba.p3c.pmd.I18nResources;
          -import com.alibaba.p3c.pmd.lang.AbstractXpathRule;
          -import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils;
          +package com.xenoamess.p3c.pmd.lang.java.rule.naming;
           
          +import com.xenoamess.p3c.pmd.I18nResources;
          +import com.xenoamess.p3c.pmd.lang.AbstractAliXpathRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils;
           import net.sourceforge.pmd.lang.ast.Node;
           import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
           
          @@ -28,9 +27,9 @@
            * @author changle.lq
            * @date 2017/04/16
            */
          -public class AbstractClassShouldStartWithAbstractNamingRule extends AbstractXpathRule {
          +public class AbstractClassShouldStartWithAbstractNamingRule extends AbstractAliXpathRule {
               private static final String XPATH = "//ClassOrInterfaceDeclaration"
          -        + " [@Abstract='true' and @Interface='false'][not (matches(@Image,'^(Abstract|Base).*'))]";
          +            + " [@Abstract='true' and @Interface='false'][not (matches(@Image,'^(Abstract|Base).*'))]";
           
               public AbstractClassShouldStartWithAbstractNamingRule() {
                   setXPath(XPATH);
          @@ -40,8 +39,8 @@ public AbstractClassShouldStartWithAbstractNamingRule() {
               public void addViolation(Object data, Node node, String arg) {
                   if (node instanceof ASTClassOrInterfaceDeclaration) {
                       ViolationUtils.addViolationWithPrecisePosition(this, node, data,
          -                I18nResources.getMessage("java.naming.AbstractClassShouldStartWithAbstractNamingRule.violation.msg",
          -                    node.getImage()));
          +                    I18nResources.getMessage("java.naming.AbstractClassShouldStartWithAbstractNamingRule.violation.msg",
          +                            node.getImage()));
                   } else {
                       super.addViolation(data, node, arg);
                   }
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/ArrayNamingShouldHaveBracketRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/ArrayNamingShouldHaveBracketRule.java
          similarity index 69%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/ArrayNamingShouldHaveBracketRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/ArrayNamingShouldHaveBracketRule.java
          index 516b060ea..2c382270f 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/ArrayNamingShouldHaveBracketRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/ArrayNamingShouldHaveBracketRule.java
          @@ -13,12 +13,11 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.naming;
          -
          -import com.alibaba.p3c.pmd.I18nResources;
          -import com.alibaba.p3c.pmd.lang.AbstractXpathRule;
          -import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils;
          +package com.xenoamess.p3c.pmd.lang.java.rule.naming;
           
          +import com.xenoamess.p3c.pmd.I18nResources;
          +import com.xenoamess.p3c.pmd.lang.AbstractAliXpathRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils;
           import net.sourceforge.pmd.lang.ast.Node;
           
           /**
          @@ -27,9 +26,9 @@
            * @author changle.lq
            * @date 2017/04/16
            */
          -public class ArrayNamingShouldHaveBracketRule extends AbstractXpathRule {
          +public class ArrayNamingShouldHaveBracketRule extends AbstractAliXpathRule {
               private static final String XPATH = "//VariableDeclaratorId[../..[@Array = 'true']]"
          -        + "[../../Type/ReferenceType[@Array != 'true']]";
          +            + "[../../Type/ReferenceType[@Array != 'true']]";
           
               public ArrayNamingShouldHaveBracketRule() {
                   setXPath(XPATH);
          @@ -38,7 +37,7 @@ public ArrayNamingShouldHaveBracketRule() {
               @Override
               public void addViolation(Object data, Node node, String arg) {
                   ViolationUtils.addViolationWithPrecisePosition(this, node, data,
          -            I18nResources.getMessage("java.naming.ArrayNamingShouldHaveBracketRule.violation.msg",
          -                node.getImage()));
          +                I18nResources.getMessage("java.naming.ArrayNamingShouldHaveBracketRule.violation.msg",
          +                        node.getImage()));
               }
           }
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/AvoidStartWithDollarAndUnderLineNamingRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/AvoidStartWithDollarAndUnderLineNamingRule.java
          similarity index 88%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/AvoidStartWithDollarAndUnderLineNamingRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/AvoidStartWithDollarAndUnderLineNamingRule.java
          index 562d95428..e2478c337 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/AvoidStartWithDollarAndUnderLineNamingRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/AvoidStartWithDollarAndUnderLineNamingRule.java
          @@ -13,12 +13,11 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.naming;
          -
          -import com.alibaba.p3c.pmd.I18nResources;
          -import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule;
          -import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils;
          +package com.xenoamess.p3c.pmd.lang.java.rule.naming;
           
          +import com.xenoamess.p3c.pmd.I18nResources;
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils;
           import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
           import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclarator;
           import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
          @@ -33,7 +32,7 @@ public class AvoidStartWithDollarAndUnderLineNamingRule extends AbstractAliRule
               private static final String DOLLAR = "$";
               private static final String UNDERSCORE = "_";
               private static final String FORMAT = I18nResources.getMessage(
          -        "java.naming.AvoidStartWithDollarAndUnderLineNamingRule.violation.msg");
          +            "java.naming.AvoidStartWithDollarAndUnderLineNamingRule.violation.msg");
           
               @Override
               public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/BooleanPropertyShouldNotStartWithIsRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/BooleanPropertyShouldNotStartWithIsRule.java
          similarity index 61%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/BooleanPropertyShouldNotStartWithIsRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/BooleanPropertyShouldNotStartWithIsRule.java
          index 368ee6a94..7b81f587a 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/BooleanPropertyShouldNotStartWithIsRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/BooleanPropertyShouldNotStartWithIsRule.java
          @@ -13,12 +13,11 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.naming;
          -
          -import com.alibaba.p3c.pmd.I18nResources;
          -import com.alibaba.p3c.pmd.lang.AbstractXpathRule;
          -import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils;
          +package com.xenoamess.p3c.pmd.lang.java.rule.naming;
           
          +import com.xenoamess.p3c.pmd.I18nResources;
          +import com.xenoamess.p3c.pmd.lang.AbstractAliXpathRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils;
           import net.sourceforge.pmd.lang.ast.Node;
           import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
           
          @@ -29,11 +28,11 @@
            * @author changle.lq
            * @date 2017/04/16
            */
          -public class BooleanPropertyShouldNotStartWithIsRule extends AbstractXpathRule {
          +public class BooleanPropertyShouldNotStartWithIsRule extends AbstractAliXpathRule {
               private static final String XPATH = "//VariableDeclaratorId[(ancestor::ClassOrInterfaceDeclaration)["
          -        + "@Interface='false' and ( ends-with(@Image, 'DO') or ends-with(@Image, 'DTO')"
          -        + " or ends-with(@Image, 'VO') or ends-with(@Image, 'DAO'))]]"
          -        + "[../../../FieldDeclaration/Type/PrimitiveType[@Image = 'boolean']][.[ starts-with(@Image, 'is')]]";
          +            + "@Interface='false' and ( ends-with(@SimpleName, 'DO') or ends-with(@SimpleName, 'DTO')"
          +            + " or ends-with(@SimpleName, 'VO') or ends-with(@SimpleName, 'DAO'))]]"
          +            + "[../../../FieldDeclaration/Type/PrimitiveType[@Image = 'boolean']][.[ starts-with(@Name, 'is')]]";
           
               public BooleanPropertyShouldNotStartWithIsRule() {
                   setXPath(XPATH);
          @@ -42,9 +41,14 @@ public BooleanPropertyShouldNotStartWithIsRule() {
               @Override
               public void addViolation(Object data, Node node, String arg) {
                   if (node instanceof ASTVariableDeclaratorId) {
          -            ViolationUtils.addViolationWithPrecisePosition(this, node, data,
          -                I18nResources.getMessage("java.naming.BooleanPropertyShouldNotStartWithIsRule.violation.msg",
          -                    node.getImage()));
          +            ViolationUtils.addViolationWithPrecisePosition(
          +                    this,
          +                    node,
          +                    data,
          +                    I18nResources.getMessage("java.naming.BooleanPropertyShouldNotStartWithIsRule.violation.msg",
          +                            node.getImage()
          +                    )
          +            );
                   } else {
                       super.addViolation(data, node, arg);
                   }
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/ClassNamingShouldBeCamelRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/ClassNamingShouldBeCamelRule.java
          similarity index 63%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/ClassNamingShouldBeCamelRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/ClassNamingShouldBeCamelRule.java
          index 57ead3df3..53bc334ed 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/ClassNamingShouldBeCamelRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/ClassNamingShouldBeCamelRule.java
          @@ -13,18 +13,17 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.naming;
          +package com.xenoamess.p3c.pmd.lang.java.rule.naming;
          +
          +import com.xenoamess.p3c.pmd.I18nResources;
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils;
          +import com.xenoamess.p3c.pmd.lang.java.util.namelist.NameListConfig;
          +import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
           
           import java.util.List;
           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.ViolationUtils;
          -import com.alibaba.p3c.pmd.lang.java.util.namelist.NameListConfig;
          -
          -import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
          -
           /**
            * [Mandatory] Class names should be nouns in UpperCamelCase except domain models: DO, BO, DTO, VO, etc.
            *
          @@ -34,14 +33,18 @@
           public class ClassNamingShouldBeCamelRule extends AbstractAliRule {
           
               private static final Pattern PATTERN
          -        = Pattern.compile("^I?([A-Z][a-z0-9]+)+(([A-Z])|(DO|DTO|VO|DAO|BO|DAOImpl|YunOS|AO|PO))?$");
          +            = Pattern.compile("^I?([A-Z][a-z0-9]+)+(([A-Z])|(DO|DTO|VO|DAO|BO|DAOImpl|YunOS|AO|PO|DOMapper))?$");
           
          -    private static final List CLASS_NAMING_WHITE_LIST = NameListConfig.NAME_LIST_SERVICE.getNameList(
          -        ClassNamingShouldBeCamelRule.class.getSimpleName(), "CLASS_NAMING_WHITE_LIST");
          +    private static List getClassNamingWhiteList() {
          +        return NameListConfig.getNameListService().getNameList(
          +                ClassNamingShouldBeCamelRule.class.getSimpleName(),
          +                "CLASS_NAMING_WHITE_LIST"
          +        );
          +    }
           
               @Override
               public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
          -        for (String s : CLASS_NAMING_WHITE_LIST) {
          +        for (String s : getClassNamingWhiteList()) {
                       if (node.getImage().contains(s)) {
                           return super.visit(node, data);
                       }
          @@ -50,8 +53,8 @@ public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
                       return super.visit(node, data);
                   }
                   ViolationUtils.addViolationWithPrecisePosition(this, node, data,
          -            I18nResources.getMessage("java.naming.ClassNamingShouldBeCamelRule.violation.msg",
          -                node.getImage()));
          +                I18nResources.getMessage("java.naming.ClassNamingShouldBeCamelRule.violation.msg",
          +                        node.getImage()));
           
                   return super.visit(node, data);
               }
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/ConstantFieldShouldBeUpperCaseRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/ConstantFieldShouldBeUpperCaseRule.java
          similarity index 63%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/ConstantFieldShouldBeUpperCaseRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/ConstantFieldShouldBeUpperCaseRule.java
          index 1b7585b17..104c20bae 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/ConstantFieldShouldBeUpperCaseRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/ConstantFieldShouldBeUpperCaseRule.java
          @@ -13,20 +13,19 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.naming;
          -
          -import java.util.HashSet;
          -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.ViolationUtils;
          -import com.alibaba.p3c.pmd.lang.java.util.namelist.NameListConfig;
          +package com.xenoamess.p3c.pmd.lang.java.rule.naming;
           
          +import com.xenoamess.p3c.pmd.I18nResources;
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils;
          +import com.xenoamess.p3c.pmd.lang.java.util.namelist.NameListConfig;
           import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType;
           import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration;
           import org.apache.commons.lang3.StringUtils;
           
          +import java.util.HashSet;
          +import java.util.Set;
          +
           /**
            * [Mandatory] Constant variable names should be written in upper characters separated by underscores. These names
            * should be semantically complete and clear.
          @@ -36,10 +35,20 @@
            */
           public class ConstantFieldShouldBeUpperCaseRule extends AbstractAliRule {
               private static final String SERVICE_SUFFIX = "Service";
          -    private static final Set LOG_VARIABLE_TYPE_SET = new HashSet<>(NameListConfig.NAME_LIST_SERVICE.getNameList(
          -        "ConstantFieldShouldBeUpperCaseRule", "LOG_VARIABLE_TYPE_SET"));
          -    private static final Set WHITE_LIST = new HashSet<>(NameListConfig.NAME_LIST_SERVICE.getNameList(
          -        "ConstantFieldShouldBeUpperCaseRule", "WHITE_LIST"));
          +
          +    private static Set getLogVariableTypeSet() {
          +        return new HashSet<>(NameListConfig.getNameListService().getNameList(
          +                "ConstantFieldShouldBeUpperCaseRule",
          +                "LOG_VARIABLE_TYPE_SET")
          +        );
          +    }
          +
          +    private static Set getWhiteList() {
          +        return new HashSet<>(NameListConfig.getNameListService().getNameList(
          +                "ConstantFieldShouldBeUpperCaseRule",
          +                "WHITE_LIST")
          +        );
          +    }
           
               @Override
               public Object visit(ASTFieldDeclaration node, Object data) {
          @@ -48,21 +57,21 @@ public Object visit(ASTFieldDeclaration node, Object data) {
                   }
                   //If the variable is of type Log  or Logger,do not check
                   ASTClassOrInterfaceType classOrInterfaceType = node.getFirstDescendantOfType(ASTClassOrInterfaceType.class);
          -        if (classOrInterfaceType != null && LOG_VARIABLE_TYPE_SET.contains(classOrInterfaceType.getImage())) {
          +        if (classOrInterfaceType != null && getLogVariableTypeSet().contains(classOrInterfaceType.getImage())) {
                       return super.visit(node, data);
                   }
                   //filter by white list,such as the serialVersionUID
          -        String constantName = node.jjtGetChild(1).jjtGetChild(0).getImage();
          -        boolean inWhiteList = StringUtils.isEmpty(constantName) || WHITE_LIST.contains(constantName)
          -            || constantName.endsWith(SERVICE_SUFFIX);
          +        String constantName = node.getChild(1).getChild(0).getImage();
          +        boolean inWhiteList = StringUtils.isEmpty(constantName) || getWhiteList().contains(constantName)
          +                || constantName.endsWith(SERVICE_SUFFIX);
                   if (inWhiteList) {
                       return super.visit(node, data);
                   }
                   //Constant should be upper
                   if (!(constantName.equals(constantName.toUpperCase()))) {
                       ViolationUtils.addViolationWithPrecisePosition(this, node, data,
          -                I18nResources.getMessage("java.naming.ConstantFieldShouldBeUpperCaseRule.violation.msg",
          -                    constantName));
          +                    I18nResources.getMessage("java.naming.ConstantFieldShouldBeUpperCaseRule.violation.msg",
          +                            constantName));
                   }
                   return super.visit(node, data);
               }
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/ExceptionClassShouldEndWithExceptionRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/ExceptionClassShouldEndWithExceptionRule.java
          similarity index 74%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/ExceptionClassShouldEndWithExceptionRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/ExceptionClassShouldEndWithExceptionRule.java
          index 2e5cb3d79..edddf606a 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/ExceptionClassShouldEndWithExceptionRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/ExceptionClassShouldEndWithExceptionRule.java
          @@ -13,12 +13,11 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.naming;
          -
          -import com.alibaba.p3c.pmd.I18nResources;
          -import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule;
          -import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils;
          +package com.xenoamess.p3c.pmd.lang.java.rule.naming;
           
          +import com.xenoamess.p3c.pmd.I18nResources;
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils;
           import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
           import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType;
           import net.sourceforge.pmd.lang.java.ast.ASTExtendsList;
          @@ -43,14 +42,14 @@ public Object visit(ASTExtendsList node, Object data) {
                   }
           
                   ASTClassOrInterfaceDeclaration astClassOrInterfaceDeclaration = node.getFirstParentOfType(
          -            ASTClassOrInterfaceDeclaration.class);
          +                ASTClassOrInterfaceDeclaration.class);
                   boolean isExceptionViolation = astClassOrInterfaceDeclaration != null
          -            && StringUtils.isNotEmpty(astClassOrInterfaceDeclaration.getImage())
          -            && !astClassOrInterfaceDeclaration.getImage().endsWith(EXCEPTION_END_SUFFIX);
          +                && StringUtils.isNotEmpty(astClassOrInterfaceDeclaration.getImage())
          +                && !astClassOrInterfaceDeclaration.getImage().endsWith(EXCEPTION_END_SUFFIX);
                   if (isExceptionViolation) {
                       ViolationUtils.addViolationWithPrecisePosition(this, astClassOrInterfaceDeclaration, data,
          -                I18nResources.getMessage("java.naming.ExceptionClassShouldEndWithExceptionRule.violation.msg",
          -                    astClassOrInterfaceDeclaration.getImage()));
          +                    I18nResources.getMessage("java.naming.ExceptionClassShouldEndWithExceptionRule.violation.msg",
          +                            astClassOrInterfaceDeclaration.getImage()));
                   }
                   return super.visit(node, data);
               }
          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/xenoamess/p3c/pmd/lang/java/rule/naming/LowerCamelCaseVariableNamingRule.java
          similarity index 59%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/LowerCamelCaseVariableNamingRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/LowerCamelCaseVariableNamingRule.java
          index e009beff4..b6d7ca07d 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/LowerCamelCaseVariableNamingRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/LowerCamelCaseVariableNamingRule.java
          @@ -13,15 +13,13 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -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;
          +package com.xenoamess.p3c.pmd.lang.java.rule.naming;
           
          +import com.xenoamess.p3c.pmd.I18nResources;
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.StringAndCharConstants;
          +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils;
          +import com.xenoamess.p3c.pmd.lang.java.util.namelist.NameListConfig;
           import net.sourceforge.pmd.lang.ast.Node;
           import net.sourceforge.pmd.lang.java.ast.ASTAnnotationTypeDeclaration;
           import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration;
          @@ -29,6 +27,9 @@
           import net.sourceforge.pmd.lang.java.ast.ASTTypeDeclaration;
           import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
           
          +import java.util.List;
          +import java.util.regex.Pattern;
          +
           /**
            * [Mandatory] Method names, parameter names, member variable names, and local variable names should be written in
            * lowerCamelCase.
          @@ -39,24 +40,39 @@
           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|BO|DOList|DTOList|VOList|DAOList|BOList|X|Y|Z|UDF|UDAF|[A-Z])?$");
          +    private final Pattern pattern = Pattern.compile("^[a-z][a-z0-9]*([A-Z][a-z0-9]+)*" +
          +            "(DO|DTO|VO|DAO|BO|DOList|DTOList|VOList|DAOList|BOList|X|Y|Z|UDF|UDAF|[A-Z])?$");
          +    private final String STRING_CLASS_NAME_OVERRIDE = "java.lang.Override";
          +
          +    private static List getWhiteList() {
          +        return NameListConfig.getNameListService().getNameList(
          +                LowerCamelCaseVariableNamingRule.class.getSimpleName(),
          +                "WHITE_LIST"
          +        );
          +    }
           
               @Override
               public Object visit(final ASTVariableDeclaratorId node, Object data) {
          +        for (String s : getWhiteList()) {
          +            if (node.getImage().contains(s)) {
          +                return super.visit(node, 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);
          +        Node jjtGetChild = typeDeclaration.getChild(0);
                   if (jjtGetChild instanceof ASTAnnotationTypeDeclaration) {
                       return super.visit(node, data);
                   }
           
                   ASTFieldDeclaration astFieldDeclaration = node.getFirstParentOfType(ASTFieldDeclaration.class);
                   boolean isNotCheck = astFieldDeclaration != null && (astFieldDeclaration.isFinal() || astFieldDeclaration
          -            .isStatic());
          +                .isStatic());
                   if (isNotCheck) {
                       return super.visit(node, data);
                   }
          @@ -64,17 +80,37 @@ public Object visit(final ASTVariableDeclaratorId node, Object data) {
                   // variable naming violate lowerCamelCase
                   if (!(pattern.matcher(node.getImage()).matches())) {
                       ViolationUtils.addViolationWithPrecisePosition(this, node, data,
          -                I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".variable", node.getImage()));
          +                    I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".variable", node.getImage()));
                   }
                   return super.visit(node, data);
               }
           
               @Override
               public Object visit(ASTMethodDeclarator node, Object data) {
          +        for (String s : getWhiteList()) {
          +            if (node.getImage().contains(s)) {
          +                return super.visit(node, data);
          +            }
          +        }
          +
          +        {
          +            // add logic: DO NOT do this analyse to all function with @Override annotation on
          +            // reason: If we can change its parent class
          +            // (means the parent class also follows p3c, notice that not all parent classes be in a same project,
          +            // it can be from a lib sometimes.), we just alarm there.
          +            //
          +            // Otherwise, we can do nothing to this, as it is just an override, and can NOT do the rename.
          +            //
          +            // In each situation, alarm in the child class is meaningless.
          +            if (node.getParent().isAnnotationPresent(STRING_CLASS_NAME_OVERRIDE)) {
          +                return super.visit(node, data);
          +            }
          +        }
          +
                   if (!variableNamingStartOrEndWithDollarAndUnderLine(node.getImage())) {
                       if (!(pattern.matcher(node.getImage()).matches())) {
                           ViolationUtils.addViolationWithPrecisePosition(this, node, data,
          -                    I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".method", node.getImage()));
          +                        I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".method", node.getImage()));
                       }
                   }
                   return super.visit(node, data);
          @@ -88,6 +124,6 @@ public Object visit(ASTAnnotationTypeDeclaration node, Object data) {
           
               private boolean variableNamingStartOrEndWithDollarAndUnderLine(String variable) {
                   return variable.startsWith(StringAndCharConstants.DOLLAR)
          -            || variable.startsWith(StringAndCharConstants.UNDERSCORE);
          +                || variable.startsWith(StringAndCharConstants.UNDERSCORE);
               }
           }
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/PackageNamingRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/PackageNamingRule.java
          similarity index 72%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/PackageNamingRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/PackageNamingRule.java
          index 6bd9175ff..16f5769bd 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/PackageNamingRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/PackageNamingRule.java
          @@ -13,12 +13,11 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.naming;
          -
          -import com.alibaba.p3c.pmd.I18nResources;
          -import com.alibaba.p3c.pmd.lang.AbstractXpathRule;
          -import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils;
          +package com.xenoamess.p3c.pmd.lang.java.rule.naming;
           
          +import com.xenoamess.p3c.pmd.I18nResources;
          +import com.xenoamess.p3c.pmd.lang.AbstractAliXpathRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils;
           import net.sourceforge.pmd.lang.ast.Node;
           
           /**
          @@ -28,9 +27,9 @@
            * @author changle.lq
            * @date 2017/04/16
            */
          -public class PackageNamingRule extends AbstractXpathRule {
          +public class PackageNamingRule extends AbstractAliXpathRule {
               private static final String XPATH = "//PackageDeclaration/Name"
          -        + "[not (matches(@Image, '^[a-z0-9]+(\\.[a-z][a-z0-9]*)*$'))]";
          +            + "[not (matches(@Image, '^[a-z0-9]+(\\.[a-z][a-z0-9]*)*$'))]";
           
               public PackageNamingRule() {
                   setXPath(XPATH);
          @@ -39,6 +38,6 @@ public PackageNamingRule() {
               @Override
               public void addViolation(Object data, Node node, String arg) {
                   ViolationUtils.addViolationWithPrecisePosition(this, node, data,
          -            I18nResources.getMessage("java.naming.PackageNamingRule.violation.msg", node.getImage()));
          +                I18nResources.getMessage("java.naming.PackageNamingRule.violation.msg", node.getImage()));
               }
           }
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/ServiceOrDaoClassShouldEndWithImplRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/ServiceOrDaoClassShouldEndWithImplRule.java
          similarity index 65%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/ServiceOrDaoClassShouldEndWithImplRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/ServiceOrDaoClassShouldEndWithImplRule.java
          index 35cfd0d45..f09b042ce 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/ServiceOrDaoClassShouldEndWithImplRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/ServiceOrDaoClassShouldEndWithImplRule.java
          @@ -13,12 +13,11 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.naming;
          -
          -import com.alibaba.p3c.pmd.I18nResources;
          -import com.alibaba.p3c.pmd.lang.AbstractXpathRule;
          -import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils;
          +package com.xenoamess.p3c.pmd.lang.java.rule.naming;
           
          +import com.xenoamess.p3c.pmd.I18nResources;
          +import com.xenoamess.p3c.pmd.lang.AbstractAliXpathRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils;
           import net.sourceforge.pmd.lang.ast.Node;
           
           /**
          @@ -28,11 +27,12 @@
            * @author changle.lq
            * @date 2017/04/16
            */
          -public class ServiceOrDaoClassShouldEndWithImplRule extends AbstractXpathRule {
          +public class ServiceOrDaoClassShouldEndWithImplRule extends AbstractAliXpathRule {
               private static final String XPATH = "//ClassOrInterfaceDeclaration"
          -        + "[ .[@Interface='false'] and .[@Abstract='false'] and ./ImplementsList/ClassOrInterfaceType[ ends-with(@Image, 'Service') or "
          -        + "ends-with(@Image, 'DAO')]]"
          -        + "[not(.[ ends-with(@Image, 'Impl')])]";
          +            + "[ .[@Interface='false'] and .[@Abstract='false'] and ./ImplementsList/ClassOrInterfaceType[ ends-with" +
          +            "(@Image, 'Service') or "
          +            + "ends-with(@Image, 'DAO')]]"
          +            + "[not(.[ ends-with(@SimpleName, 'Impl')])]";
           
               public ServiceOrDaoClassShouldEndWithImplRule() {
                   setXPath(XPATH);
          @@ -41,7 +41,7 @@ public ServiceOrDaoClassShouldEndWithImplRule() {
               @Override
               public void addViolation(Object data, Node node, String arg) {
                   ViolationUtils.addViolationWithPrecisePosition(this, node, data,
          -            I18nResources.getMessage("java.naming.ServiceOrDaoClassShouldEndWithImplRule.violation.msg",
          -                node.getImage()));
          +                I18nResources.getMessage("java.naming.ServiceOrDaoClassShouldEndWithImplRule.violation.msg",
          +                        node.getImage()));
               }
           }
          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/xenoamess/p3c/pmd/lang/java/rule/naming/TestClassShouldEndWithTestNamingRule.java
          similarity index 69%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/TestClassShouldEndWithTestNamingRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/TestClassShouldEndWithTestNamingRule.java
          index 50977304b..73f27ab23 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/TestClassShouldEndWithTestNamingRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/TestClassShouldEndWithTestNamingRule.java
          @@ -13,18 +13,17 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.naming;
          -
          -import java.util.List;
          -
          -import com.alibaba.p3c.pmd.I18nResources;
          -import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils;
          +package com.xenoamess.p3c.pmd.lang.java.rule.naming;
           
          +import com.xenoamess.p3c.pmd.I18nResources;
          +import com.xenoamess.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.AbstractJUnitRule;
           
          +import java.util.List;
          +
           /**
            * [Mandatory] Test cases shall be started with the class names to be tested and ended with Test.
            *
          @@ -36,6 +35,24 @@ public class TestClassShouldEndWithTestNamingRule extends AbstractJUnitRule {
           
               @Override
               public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
          +        boolean oldJunit3Class = isJUnit3Class;
          +        boolean oldJunit4Class = isJUnit4Class;
          +        boolean oldJunit5Class = isJUnit5Class;
          +
          +        Object res;
          +        try {
          +            analyzeJUnitClass(node);
          +            res = this.visitInternal(node, data);
          +        } finally {
          +            isJUnit3Class = oldJunit3Class;
          +            isJUnit4Class = oldJunit4Class;
          +            isJUnit5Class = oldJunit5Class;
          +        }
          +
          +        return res;
          +    }
          +
          +    private Object visitInternal(ASTClassOrInterfaceDeclaration node, Object data) {
                   if (node.isAbstract() || node.isInterface() || node.isNested()) {
                       return super.visit(node, data);
                   }
          @@ -51,10 +68,10 @@ public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
                       }
                   }
           
          -        if ((testsFound) && (!(node.getImage().endsWith(TEST_SUFFIX)))) {
          +        if ((testsFound) && (!(node.getSimpleName().endsWith(TEST_SUFFIX)))) {
                       ViolationUtils.addViolationWithPrecisePosition(this, node, data,
          -                I18nResources.getMessage("java.naming.TestClassShouldEndWithTestNamingRule.violation.msg",
          -                    node.getImage()));
          +                    I18nResources.getMessage("java.naming.TestClassShouldEndWithTestNamingRule.violation.msg",
          +                            node.getSimpleName()));
                   }
           
                   return super.visit(node, data);
          @@ -77,12 +94,18 @@ public void setMessage(String message) {
           
               @Override
               public void addViolationWithMessage(Object data, Node node, String message) {
          +        if (ViolationUtils.shouldIgnoreViolation(this.getClass(), node)) {
          +            return;
          +        }
                   super.addViolationWithMessage(data, node, I18nResources.getMessageWithExceptionHandled(message));
               }
           
               @Override
               public void addViolationWithMessage(Object data, Node node, String message, Object[] args) {
          +        if (ViolationUtils.shouldIgnoreViolation(this.getClass(), node)) {
          +            return;
          +        }
                   super.addViolationWithMessage(data, node,
          -            String.format(I18nResources.getMessageWithExceptionHandled(message), args));
          +                String.format(I18nResources.getMessageWithExceptionHandled(message), args));
               }
           }
          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/xenoamess/p3c/pmd/lang/java/rule/oop/BigDecimalAvoidDoubleConstructorRule.java
          similarity index 63%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/BigDecimalAvoidDoubleConstructorRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/oop/BigDecimalAvoidDoubleConstructorRule.java
          index 5b724ca86..ea977f8b8 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/BigDecimalAvoidDoubleConstructorRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/oop/BigDecimalAvoidDoubleConstructorRule.java
          @@ -13,13 +13,11 @@
            * 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;
          +package com.xenoamess.p3c.pmd.lang.java.rule.oop;
           
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils;
          +import net.sourceforge.pmd.lang.ast.GenericToken;
           import net.sourceforge.pmd.lang.ast.Node;
           import net.sourceforge.pmd.lang.java.ast.ASTLiteral;
           import net.sourceforge.pmd.lang.java.ast.ASTName;
          @@ -27,6 +25,8 @@
           import net.sourceforge.pmd.lang.java.ast.ASTVariableInitializer;
           import org.jaxen.JaxenException;
           
          +import java.util.List;
          +
           /**
            * [Mandatory] Avoid using the constructor BigDecimal(double) to convert double value to a BigDecimal object.
            *
          @@ -36,8 +36,15 @@
           public class BigDecimalAvoidDoubleConstructorRule extends AbstractAliRule {
           
               private static final String XPATH =
          -        "Expression/PrimaryExpression/PrimaryPrefix/AllocationExpression/Arguments[preceding-sibling::ClassOrInterfaceType[@Image = 'BigDecimal']]"
          -            + "/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix";
          +            "Expression/PrimaryExpression/PrimaryPrefix/AllocationExpression/Arguments[preceding-sibling" +
          +                    "::ClassOrInterfaceType[@Image = 'BigDecimal']]"
          +                    + "/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix";
          +
          +    private static final String STRING_DOUBLE = "Double";
          +
          +    private static final String STRING_TO_HEX_STRING = "toHexString";
          +
          +    private static final String STRING_TO_STRING = "toString";
           
               @Override
               public Object visit(ASTVariableInitializer node, Object data) {
          @@ -46,10 +53,10 @@ public Object visit(ASTVariableInitializer node, Object data) {
                       if (invocations == null || invocations.isEmpty()) {
                           return super.visit(node, data);
                       }
          -            ASTPrimaryPrefix expression = (ASTPrimaryPrefix)invocations.get(0);
          +            ASTPrimaryPrefix expression = (ASTPrimaryPrefix) invocations.get(0);
           
                       if (isDoubleLiteral(expression) || isDoubleVariable(expression)) {
          -                    addViolationWithMessage(data, node,
          +                addViolationWithMessage(data, node,
                                   "java.oop.BigDecimalAvoidDoubleConstructorRule.violation.msg", null);
                       }
           
          @@ -63,7 +70,7 @@ public Object visit(ASTVariableInitializer node, Object data) {
               @Override
               public void addViolation(Object data, Node node, String arg) {
                   ViolationUtils.addViolationWithPrecisePosition(this, node, data,
          -            "java.oop.BigDecimalAvoidDoubleConstructorRule.violation.msg");
          +                "java.oop.BigDecimalAvoidDoubleConstructorRule.violation.msg");
               }
           
               private boolean isDoubleLiteral(ASTPrimaryPrefix node) {
          @@ -73,6 +80,17 @@ private boolean isDoubleLiteral(ASTPrimaryPrefix node) {
           
               private boolean isDoubleVariable(ASTPrimaryPrefix node) {
                   ASTName name = node.getFirstChildOfType(ASTName.class);
          -        return name != null && Double.class ==  name.getType();
          +        if (!(name != null && Double.class == name.getType())) {
          +            return false;
          +        }
          +        GenericToken firstToken = node.jjtGetFirstToken();
          +        GenericToken lastToken = node.jjtGetLastToken();
          +
          +        return !(STRING_DOUBLE.equals(firstToken.getImage()) &&
          +                (
          +                        STRING_TO_HEX_STRING.equals(lastToken.getImage())
          +                                || STRING_TO_STRING.equals(lastToken.getImage())
          +                )
          +        );
               }
           }
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/EqualsAvoidNullRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/oop/EqualsAvoidNullRule.java
          similarity index 80%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/EqualsAvoidNullRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/oop/EqualsAvoidNullRule.java
          index dc2aadb4b..51ea9b132 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/EqualsAvoidNullRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/oop/EqualsAvoidNullRule.java
          @@ -13,14 +13,11 @@
            * 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.rule.util.NodeUtils;
          -import com.alibaba.p3c.pmd.lang.java.util.StringAndCharConstants;
          +package com.xenoamess.p3c.pmd.lang.java.rule.oop;
           
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
          +import com.xenoamess.p3c.pmd.lang.java.rule.util.NodeUtils;
          +import com.xenoamess.p3c.pmd.lang.java.util.StringAndCharConstants;
           import net.sourceforge.pmd.lang.ast.Node;
           import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
           import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration;
          @@ -33,6 +30,8 @@
           import net.sourceforge.pmd.lang.java.ast.Token;
           import org.jaxen.JaxenException;
           
          +import java.util.List;
          +
           /**
            * [Mandatory] Since NullPointerException can possibly be thrown while calling the equals method of Object,
            * equals should be invoked by a constant or an object that is definitely not null.
          @@ -43,14 +42,14 @@
           public class EqualsAvoidNullRule extends AbstractAliRule {
           
               private static final String XPATH = "//PrimaryExpression[" + "(PrimaryPrefix[Name[(ends-with(@Image, '.equals'))]]|"
          -        + "PrimarySuffix[@Image='equals'])"
          -        + "[(../PrimarySuffix/Arguments/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix) and "
          -        + "( count(../PrimarySuffix/Arguments/ArgumentList/Expression) = 1 )]]"
          -        + "[not(ancestor::Expression/ConditionalAndExpression//EqualityExpression[@Image='!=']//NullLiteral)]"
          -        + "[not(ancestor::Expression/ConditionalOrExpression//EqualityExpression[@Image='==']//NullLiteral)]";
          +            + "PrimarySuffix[@Image='equals'])"
          +            + "[(../PrimarySuffix/Arguments/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix) and "
          +            + "( count(../PrimarySuffix/Arguments/ArgumentList/Expression) = 1 )]]"
          +            + "[not(ancestor::Expression/ConditionalAndExpression//EqualityExpression[@Image='!=']//NullLiteral)]"
          +            + "[not(ancestor::Expression/ConditionalOrExpression//EqualityExpression[@Image='==']//NullLiteral)]";
           
               private static final String INVOCATION_PREFIX_XPATH
          -        = "PrimarySuffix/Arguments/ArgumentList/Expression/PrimaryExpression[not(PrimarySuffix)]/PrimaryPrefix";
          +            = "PrimarySuffix/Arguments/ArgumentList/Expression/PrimaryExpression[not(PrimarySuffix)]/PrimaryPrefix";
           
               private static final String METHOD_EQUALS = "equals";
           
          @@ -73,7 +72,7 @@ public Object visit(ASTCompilationUnit node, Object data) {
                               return super.visit(node, data);
                           }
           
          -                ASTPrimaryPrefix right = (ASTPrimaryPrefix)simpleExpressions.get(0);
          +                ASTPrimaryPrefix right = (ASTPrimaryPrefix) simpleExpressions.get(0);
                           if (right.getFirstChildOfType(ASTLiteral.class) != null) {
                               ASTLiteral literal = right.getFirstChildOfType(ASTLiteral.class);
                               if (literal.isStringLiteral()) {
          @@ -84,14 +83,14 @@ public Object visit(ASTCompilationUnit node, Object data) {
                               ASTName name = right.getFirstChildOfType(ASTName.class);
                               // TODO works only in current compilation file, by crossing files will be null
                               boolean nameInvalid = name == null || name.getNameDeclaration() == null
          -                        || name.getNameDeclaration().getNode() == null;
          +                            || name.getNameDeclaration().getNode() == null;
                               if (nameInvalid) {
                                   return super.visit(node, data);
                               }
                               Node nameNode = name.getNameDeclaration().getNode();
                               if ((nameNode instanceof ASTVariableDeclaratorId) && (nameNode.getNthParent(
          -                        2) instanceof ASTFieldDeclaration)) {
          -                        ASTFieldDeclaration field = (ASTFieldDeclaration)nameNode.getNthParent(2);
          +                            2) instanceof ASTFieldDeclaration)) {
          +                        ASTFieldDeclaration field = (ASTFieldDeclaration) nameNode.getNthParent(2);
                                   if (NodeUtils.isConstant(field)) {
                                       addRuleViolation(data, invocation);
                                   }
          @@ -113,7 +112,7 @@ private boolean callerIsLiteral(Node equalsInvocation) {
               }
           
               private String getInvocationName(AbstractJavaNode javaNode) {
          -        Token token = (Token)javaNode.jjtGetFirstToken();
          +        Token token = (Token) javaNode.jjtGetFirstToken();
                   StringBuilder sb = new StringBuilder(token.image).append(token.image);
                   while (token.next != null && token.next.image != null && !METHOD_EQUALS.equals(token.next.image)) {
                       token = token.next;
          @@ -127,9 +126,9 @@ private String getInvocationName(AbstractJavaNode javaNode) {
           
               private void addRuleViolation(Object data, Node invocation) {
                   if (invocation instanceof AbstractJavaNode) {
          -            AbstractJavaNode javaNode = (AbstractJavaNode)invocation;
          +            AbstractJavaNode javaNode = (AbstractJavaNode) invocation;
                       addViolationWithMessage(data, invocation, "java.oop.EqualsAvoidNullRule.violation.msg",
          -                new Object[] {getInvocationName(javaNode)});
          +                    new Object[]{getInvocationName(javaNode)});
                   } else {
                       addViolation(data, invocation);
                   }
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/PojoMustOverrideToStringRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/oop/PojoMustOverrideToStringRule.java
          similarity index 63%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/PojoMustOverrideToStringRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/oop/PojoMustOverrideToStringRule.java
          index b5193edda..b44d5d986 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/PojoMustOverrideToStringRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/oop/PojoMustOverrideToStringRule.java
          @@ -13,13 +13,12 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.oop;
          -
          -import com.alibaba.p3c.pmd.I18nResources;
          -import com.alibaba.p3c.pmd.lang.java.rule.AbstractPojoRule;
          -import com.alibaba.p3c.pmd.lang.java.util.PojoUtils;
          -import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils;
          +package com.xenoamess.p3c.pmd.lang.java.rule.oop;
           
          +import com.xenoamess.p3c.pmd.I18nResources;
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractPojoRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.PojoUtils;
          +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils;
           import net.sourceforge.pmd.lang.java.ast.ASTBlock;
           import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
           import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType;
          @@ -37,23 +36,24 @@
           public class PojoMustOverrideToStringRule extends AbstractPojoRule {
           
               private static final String XPATH = "ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/MethodDeclaration"
          -        + "[@Public='true' and MethodDeclarator[@Image='toString'] and "
          -        + "MethodDeclarator[@Image='toString' and @ParameterCount='0']]";
          +            + "[@Public='true' and @Name='toString' and @Arity='0']";
           
          -    private static final String TOSTRING_XPATH = "//PrimaryExpression[PrimaryPrefix[Name"
          -        + "[(ends-with(@Image, '.toString'))]]["
          -        + "(../PrimarySuffix/Arguments/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix/Literal[@StringLiteral"
          -        + "='true'])" + " and ( count(../PrimarySuffix/Arguments/ArgumentList/Expression) = 1 )]]"
          -        + "[not(ancestor::Expression/ConditionalAndExpression//EqualityExpression[@Image='!=']//NullLiteral)]"
          -        + "[not(ancestor::Expression/ConditionalOrExpression//EqualityExpression[@Image='==']//NullLiteral)]";
          +    private static final String TO_STRING_XPATH = "//PrimaryExpression[PrimaryPrefix[Name"
          +            + "[(ends-with(@Image, '.toString'))]]["
          +            + "(../PrimarySuffix/Arguments/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix/Literal" +
          +            "[@StringLiteral"
          +            + "='true'])" + " and ( count(../PrimarySuffix/Arguments/ArgumentList/Expression) = 1 )]]"
          +            + "[not(ancestor::Expression/ConditionalAndExpression//EqualityExpression[@Image='!=']//NullLiteral)]"
          +            + "[not(ancestor::Expression/ConditionalOrExpression//EqualityExpression[@Image='==']//NullLiteral)]";
           
               private static final String LOMBOK_NAME_XPATH = "/Name["
          -        + "(@Image='Data' and //ImportDeclaration[@ImportedName='lombok.Data' or @ImportedName='lombok'])"
          -        + " or (@Image='ToString' and //ImportDeclaration[@ImportedName='lombok.ToString' or @ImportedName='lombok'])"
          -        + " or (@Image='lombok.Data') or (@Image='lombok.ToString')]";
          +            + "(@Image='Data' and //ImportDeclaration[@ImportedName='lombok.Data' or @ImportedName='lombok'])"
          +            + " or (@Image='ToString' and //ImportDeclaration[@ImportedName='lombok.ToString' or " +
          +            "@ImportedName='lombok'])"
          +            + " or (@Image='lombok.Data') or (@Image='lombok.ToString')]";
           
               private static final String LOMBOK_XPATH = "../Annotation/MarkerAnnotation" + LOMBOK_NAME_XPATH
          -        + "|../Annotation/NormalAnnotation" + LOMBOK_NAME_XPATH;
          +            + "|../Annotation/NormalAnnotation" + LOMBOK_NAME_XPATH;
           
               private static final String MESSAGE_KEY_PREFIX = "java.oop.PojoMustOverrideToStringRule.violation.msg";
           
          @@ -72,7 +72,7 @@ public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
           
                   if (!node.hasDescendantMatchingXPath(XPATH)) {
                       ViolationUtils.addViolationWithPrecisePosition(this, node, data,
          -                I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".notostring", node.getImage()));
          +                    I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".notostring", node.getImage()));
                   } else {
                       checkForExtend(node, data);
                   }
          @@ -80,11 +80,11 @@ public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
               }
           
               private void checkForExtend(ASTClassOrInterfaceDeclaration node, Object data) {
          -    /*
          -     * The super.toString method should be called in front of the whole implementation
          -     * if the current class extends another POJO class
          -     * -> this part not checked
          -     */
          +        /*
          +         * The super.toString method should be called in front of the whole implementation
          +         * if the current class extends another POJO class
          +         * -> this part not checked
          +         */
                   ASTExtendsList extendsList = node.getFirstChildOfType(ASTExtendsList.class);
                   if (extendsList == null) {
                       return;
          @@ -95,9 +95,9 @@ private void checkForExtend(ASTClassOrInterfaceDeclaration node, Object data) {
                   }
                   try {
                       // toString() definition
          -            ASTMethodDeclaration toStringMethod = (ASTMethodDeclaration)node.findChildNodesWithXPath(XPATH).get(0);
          -            ASTBlock block = toStringMethod.getBlock();
          -            if (block.hasDescendantMatchingXPath(TOSTRING_XPATH)) {
          +            ASTMethodDeclaration toStringMethod = (ASTMethodDeclaration) node.findChildNodesWithXPath(XPATH).get(0);
          +            ASTBlock block = toStringMethod.getBody();
          +            if (block.hasDescendantMatchingXPath(TO_STRING_XPATH)) {
                           addViolationWithMessage(data, block, MESSAGE_KEY_PREFIX + ".usesuper");
                       }
                   } catch (JaxenException e) {
          @@ -107,6 +107,7 @@ private void checkForExtend(ASTClassOrInterfaceDeclaration node, Object data) {
           
               /**
                * Class with lombok @Data will be skipped
          +     * @param node node
                */
               private boolean withLombokAnnotation(ASTClassOrInterfaceDeclaration node) {
                   return node.hasDescendantMatchingXPath(LOMBOK_XPATH);
          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/xenoamess/p3c/pmd/lang/java/rule/oop/PojoMustUsePrimitiveFieldRule.java
          similarity index 82%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/PojoMustUsePrimitiveFieldRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/oop/PojoMustUsePrimitiveFieldRule.java
          index 9e42c99c1..89fba9ea0 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/PojoMustUsePrimitiveFieldRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/oop/PojoMustUsePrimitiveFieldRule.java
          @@ -13,20 +13,19 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.oop;
          +package com.xenoamess.p3c.pmd.lang.java.rule.oop;
           
          -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 com.xenoamess.p3c.pmd.lang.java.rule.AbstractPojoRule;
          +import com.xenoamess.p3c.pmd.lang.java.rule.util.NodeUtils;
          +import com.xenoamess.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;
           import net.sourceforge.pmd.lang.java.ast.ASTType;
           import org.jaxen.JaxenException;
           
          +import java.util.List;
          +
           /**
            * [Mandatory]  Rules for using primitive data types and wrapper classes:
            * 1) Members of a POJO class must be wrapper classes.
          @@ -47,10 +46,10 @@ public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
                   }
                   try {
                       List fields = node.findChildNodesWithXPath(
          -                "ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/FieldDeclaration");
          +                    "ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/FieldDeclaration");
           
                       for (Node fieldNode : fields) {
          -                ASTFieldDeclaration field = (ASTFieldDeclaration)fieldNode;
          +                ASTFieldDeclaration field = (ASTFieldDeclaration) fieldNode;
                           boolean shouldProcess = !field.isPublic() && !field.isStatic() && !field.isTransient();
                           if (!shouldProcess) {
                               continue;
          @@ -59,8 +58,8 @@ public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
                           // 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[] {VariableUtils.getVariableName(field)});
          +                            "java.oop.PojoMustUsePrimitiveFieldRule.violation.msg",
          +                            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/xenoamess/p3c/pmd/lang/java/rule/oop/PojoNoDefaultValueRule.java
          similarity index 74%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/PojoNoDefaultValueRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/oop/PojoNoDefaultValueRule.java
          index fd4e24ffc..abe9fa1ff 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/PojoNoDefaultValueRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/oop/PojoNoDefaultValueRule.java
          @@ -13,21 +13,20 @@
            * 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.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;
          +package com.xenoamess.p3c.pmd.lang.java.rule.oop;
           
          +import com.xenoamess.p3c.pmd.I18nResources;
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractPojoRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.VariableUtils;
          +import com.xenoamess.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.ASTFieldDeclaration;
           import net.sourceforge.pmd.lang.java.ast.ASTVariableInitializer;
           import org.jaxen.JaxenException;
           
          +import java.util.List;
          +
           /**
            * [Mandatory] While defining POJO classes like DO, DTO, VO, etc., do not assign any default values to the members.
            *
          @@ -43,19 +42,19 @@ public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
                   }
                   try {
                       List fields = node.findChildNodesWithXPath(
          -                "ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/FieldDeclaration");
          +                    "ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/FieldDeclaration");
           
                       for (Node fieldNode : fields) {
          -                ASTFieldDeclaration field = (ASTFieldDeclaration)fieldNode;
          +                ASTFieldDeclaration field = (ASTFieldDeclaration) fieldNode;
                           boolean shouldProcess = !field.isPublic() && !field.isFinal() && !field.isStatic() && !field
          -                    .isVolatile() &&
          -                    field.hasDescendantOfType(ASTVariableInitializer.class);
          +                        .isVolatile() &&
          +                        field.hasDescendantOfType(ASTVariableInitializer.class);
                           if (!shouldProcess) {
                               continue;
                           }
                           ViolationUtils.addViolationWithPrecisePosition(this, field, data,
          -                    I18nResources.getMessage("java.oop.PojoNoDefaultValueRule.violation.msg",
          -                        VariableUtils.getVariableName(field)));
          +                        I18nResources.getMessage("java.oop.PojoNoDefaultValueRule.violation.msg",
          +                                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/oop/StringConcatRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/oop/StringConcatRule.java
          similarity index 73%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/StringConcatRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/oop/StringConcatRule.java
          index 9583c9438..7c4e6200f 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/StringConcatRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/oop/StringConcatRule.java
          @@ -13,15 +13,12 @@
            * 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.I18nResources;
          -import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule;
          -import com.alibaba.p3c.pmd.lang.java.util.NumberConstants;
          -import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils;
          +package com.xenoamess.p3c.pmd.lang.java.rule.oop;
           
          +import com.xenoamess.p3c.pmd.I18nResources;
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.NumberConstants;
          +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils;
           import net.sourceforge.pmd.lang.ast.Node;
           import net.sourceforge.pmd.lang.java.ast.ASTAdditiveExpression;
           import net.sourceforge.pmd.lang.java.ast.ASTDoStatement;
          @@ -34,6 +31,8 @@
           import net.sourceforge.pmd.lang.symboltable.NameDeclaration;
           import org.jaxen.JaxenException;
           
          +import java.util.List;
          +
           /**
            * [Recommended] Use the append method in StringBuilder inside a loop body when concatenating multiple strings.
            *
          @@ -43,8 +42,8 @@
           public class StringConcatRule extends AbstractAliRule {
           
               private static final String XPATH =
          -        "Statement/Block//Expression[preceding-sibling::AssignmentOperator]/AdditiveExpression[(@Image = '+') and "
          -            + "count(./PrimaryExpression/PrimaryPrefix/Literal[@StringLiteral = 'true']) > 0]";
          +            "Statement/Block//Expression[preceding-sibling::AssignmentOperator]/AdditiveExpression[(@Operator = '+') and "
          +                    + "count(./PrimaryExpression/PrimaryPrefix/Literal[@StringLiteral = 'true']) > 0]";
           
               @Override
               public Object visit(ASTForStatement node, Object data) {
          @@ -67,37 +66,37 @@ public Object visit(ASTDoStatement node, Object data) {
               /**
                * Find additive assignment with string literal, then check if the assigned variable defined out of the loop,
                *
          -     * @param node
          -     * @param data
          -     * @param nodeClass
          +     * @param node node
          +     * @param data ruleContext
          +     * @param nodeClass nodeClass
                */
               private void checkStringConcat(Node node, Object data, Class nodeClass) {
                   try {
                       List additiveNodes = node.findChildNodesWithXPath(XPATH);
                       for (Node additiveNode : additiveNodes) {
          -                ASTAdditiveExpression additiveExpression = (ASTAdditiveExpression)additiveNode;
          +                ASTAdditiveExpression additiveExpression = (ASTAdditiveExpression) additiveNode;
                           Node assignmentStatement = additiveExpression.getNthParent(2);
                           if (!(assignmentStatement instanceof ASTStatementExpression)) {
                               continue;
                           }
          -                List nodes = ((ASTStatementExpression)assignmentStatement)
          -                    .findChildNodesWithXPath("PrimaryExpression/PrimaryPrefix/Name[@Image]");
          +                List nodes = ((ASTStatementExpression) assignmentStatement)
          +                        .findChildNodesWithXPath("PrimaryExpression/PrimaryPrefix/Name[@Image]");
                           if (nodes == null || nodes.size() != NumberConstants.INTEGER_SIZE_OR_LENGTH_1) {
                               continue;
                           }
          -                NameDeclaration resultVar = ((ASTName)nodes.get(0)).getNameDeclaration();
          +                NameDeclaration resultVar = ((ASTName) nodes.get(0)).getNameDeclaration();
                           if (resultVar != null && resultVar.getNode() != null) {
                               boolean isDefinedInLoop = false;
           
          -                    AbstractJavaNode loopStatement = (AbstractJavaNode)resultVar.getNode().getFirstParentOfType(
          -                        nodeClass);
          +                    AbstractJavaNode loopStatement = (AbstractJavaNode) resultVar.getNode().getFirstParentOfType(
          +                            nodeClass);
           
                               while (loopStatement != null) {
                                   if (loopStatement == node) {
                                       isDefinedInLoop = true;
                                       break;
                                   }
          -                        loopStatement = (AbstractJavaNode)loopStatement.getFirstParentOfType(nodeClass);
          +                        loopStatement = (AbstractJavaNode) loopStatement.getFirstParentOfType(nodeClass);
                               }
           
                               // if assigned variable defined in the loop then break
          @@ -106,17 +105,17 @@ private void checkStringConcat(Node node, Object data, Class nodeClass) {
                               }
                           }
                           // arguments joint by "+"
          -                for (int i = 0; i < additiveNode.jjtGetNumChildren(); i++) {
          -                    Node firstArg = additiveNode.jjtGetChild(i);
          +                for (int i = 0; i < additiveNode.getNumChildren(); i++) {
          +                    Node firstArg = additiveNode.getChild(i);
                               if (!(firstArg instanceof ASTPrimaryExpression)) {
                                   continue;
                               }
          -                    List names = ((ASTPrimaryExpression)firstArg).
          -                        findChildNodesWithXPath("./PrimaryPrefix/Name[@Image]");
          +                    List names = ((ASTPrimaryExpression) firstArg).
          +                            findChildNodesWithXPath("./PrimaryPrefix/Name[@Image]");
                               if (names == null || names.size() != NumberConstants.INTEGER_SIZE_OR_LENGTH_1) {
                                   continue;
                               }
          -                    NameDeclaration firstArgVar = ((ASTName)names.get(0)).getNameDeclaration();
          +                    NameDeclaration firstArgVar = ((ASTName) names.get(0)).getNameDeclaration();
           
                               // concat self, e.g. a = a + b;
                               if (resultVar == firstArgVar) {
          @@ -133,6 +132,6 @@ private void checkStringConcat(Node node, Object data, Class nodeClass) {
               @Override
               public void addViolation(Object data, Node node, String arg) {
                   ViolationUtils.addViolationWithPrecisePosition(this, node, data,
          -            I18nResources.getMessage("java.oop.PojoMustOverrideToStringRule.violation.msg"));
          +                I18nResources.getMessage("java.oop.PojoMustOverrideToStringRule.violation.msg"));
               }
           }
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/WrapperTypeEqualityRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/oop/WrapperTypeEqualityRule.java
          similarity index 86%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/WrapperTypeEqualityRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/oop/WrapperTypeEqualityRule.java
          index 5b6d80b6d..6a0b944dc 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/WrapperTypeEqualityRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/oop/WrapperTypeEqualityRule.java
          @@ -13,17 +13,16 @@
            * 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.rule.util.NodeUtils;
          -import com.alibaba.p3c.pmd.lang.java.util.NumberConstants;
          +package com.xenoamess.p3c.pmd.lang.java.rule.oop;
           
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
          +import com.xenoamess.p3c.pmd.lang.java.rule.util.NodeUtils;
          +import com.xenoamess.p3c.pmd.lang.java.util.NumberConstants;
           import net.sourceforge.pmd.lang.java.ast.ASTEqualityExpression;
           import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression;
           
          +import java.util.List;
          +
           /**
            * [Mandatory] The wrapper classes should be compared by equals method rather than by symbol of '==' directly.
            *
          @@ -38,7 +37,7 @@ public Object visit(ASTEqualityExpression node, Object data) {
                   final String unaryExpression = "UnaryExpression";
                   // null presents in either side of "==" or "!=" means no violation
                   if (node.hasDescendantMatchingXPath(literalPrefix)
          -            || node.hasDescendantMatchingXPath(unaryExpression)) {
          +                || node.hasDescendantMatchingXPath(unaryExpression)) {
                       return super.visit(node, data);
                   }
           
          @@ -65,9 +64,9 @@ public Object visit(ASTEqualityExpression node, Object data) {
           
               private boolean isArrayLength(ASTPrimaryExpression expression) {
                   // assume expression like "x.length" is the length of array, field with name "length" may result in
          -        // misrecognition
          +        // mis-recognition
                   return "length".equals(expression.jjtGetLastToken().getImage())
          -            && ".".equals(expression.jjtGetFirstToken().getNext().getImage());
          +                && ".".equals(expression.jjtGetFirstToken().getNext().getImage());
               }
           
           }
          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/xenoamess/p3c/pmd/lang/java/rule/orm/IbatisMethodQueryForListRule.java
          similarity index 81%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/orm/IbatisMethodQueryForListRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/orm/IbatisMethodQueryForListRule.java
          index a13f1b571..f443bfc80 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/orm/IbatisMethodQueryForListRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/orm/IbatisMethodQueryForListRule.java
          @@ -13,18 +13,12 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.orm;
          -
          -import java.util.Collections;
          -import java.util.HashSet;
          -import java.util.List;
          -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;
          +package com.xenoamess.p3c.pmd.lang.java.rule.orm;
           
          +import com.xenoamess.p3c.pmd.I18nResources;
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.VariableUtils;
          +import com.xenoamess.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.ASTCompilationUnit;
          @@ -36,6 +30,11 @@
           import org.apache.commons.lang3.StringUtils;
           import org.jaxen.JaxenException;
           
          +import java.util.Collections;
          +import java.util.HashSet;
          +import java.util.List;
          +import java.util.Set;
          +
           /**
            * [Mandatory] iBatis built in queryForList(String statementName, int start, int size) is not recommended.
            * Note: It may lead to OOM issue because its implementation is to retrieve all DB records of statementName's
          @@ -51,7 +50,7 @@ public class IbatisMethodQueryForListRule extends AbstractAliRule {
               private static final String IBATIS_QUERY_FOR_LIST_METHOD_NAME = ".queryForList";
               private static final String PRIMARY_METHOD_NAME_XPATH = "PrimaryPrefix/Name";
               private static final String PRIMARY_METHOD_ARGUMENT_XPATH
          -        = "PrimarySuffix/Arguments/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix/Literal";
          +            = "PrimarySuffix/Arguments/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix/Literal";
               private static final String FIELDS_XPATH = "ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/FieldDeclaration";
               private static final int LITERALS_SIZE = 3;
           
          @@ -62,7 +61,7 @@ public Object visit(ASTCompilationUnit node, Object data) {
                       return super.visit(node, data);
                   }
                   List classOrInterfaceDeclarations
          -            = node.findDescendantsOfType(ASTClassOrInterfaceDeclaration.class);
          +                = node.findDescendantsOfType(ASTClassOrInterfaceDeclaration.class);
                   if (classOrInterfaceDeclarations == null || classOrInterfaceDeclarations.isEmpty()) {
                       return super.visit(node, data);
                   }
          @@ -73,7 +72,7 @@ public Object visit(ASTCompilationUnit node, Object data) {
               }
           
               private void visitAstClassOrInterfaceDeclaration(ASTClassOrInterfaceDeclaration classOrInterfaceDeclaration,
          -        Object data) {
          +                                                     Object data) {
                   try {
                       List fieldDeclarations = classOrInterfaceDeclaration.findChildNodesWithXPath(FIELDS_XPATH);
                       Set sqlMapFields = getSqlMapFields(fieldDeclarations);
          @@ -81,7 +80,7 @@ private void visitAstClassOrInterfaceDeclaration(ASTClassOrInterfaceDeclaration
                           return;
                       }
                       List primaryExpressions = classOrInterfaceDeclaration.findDescendantsOfType(
          -                ASTPrimaryExpression.class);
          +                    ASTPrimaryExpression.class);
                       for (ASTPrimaryExpression primaryExpression : primaryExpressions) {
                           visitPrimaryExpression(primaryExpression, data, sqlMapFields);
                       }
          @@ -95,7 +94,7 @@ private Set getSqlMapFields(List fieldDeclarations) {
                   }
                   Set set = new HashSet<>();
                   for (Node node : fieldDeclarations) {
          -            ASTFieldDeclaration fieldDeclaration = (ASTFieldDeclaration)node;
          +            ASTFieldDeclaration fieldDeclaration = (ASTFieldDeclaration) node;
                       if (sqlMapClientField(fieldDeclaration)) {
                           set.add(VariableUtils.getVariableName(fieldDeclaration));
                       }
          @@ -106,6 +105,8 @@ private Set getSqlMapFields(List fieldDeclarations) {
               /**
                * if there is no introduction of related packages, skip the inspection
                * The import statement is generally at the start of the class, do some cleaning
          +     * @param importDeclarations importDeclarations
          +     * @return ifHasSqlMapClientImport
                */
               private boolean hasSqlMapClientImport(List importDeclarations) {
                   if (importDeclarations == null || importDeclarations.isEmpty()) {
          @@ -114,7 +115,7 @@ private boolean hasSqlMapClientImport(List importDeclarati
                   for (ASTImportDeclaration importDeclaration : importDeclarations) {
                       ASTName astName = importDeclaration.getFirstChildOfType(ASTName.class);
                       boolean hasImport = astName != null && (SQL_MAP_CLIENT_IMPORT_FULL_NAME.equals(astName.getImage())
          -                || SQL_MAP_CLIENT_IMPORT_SIMPLE_NAME.equals(astName.getImage()));
          +                    || SQL_MAP_CLIENT_IMPORT_SIMPLE_NAME.equals(astName.getImage()));
                       if (hasImport) {
                           return true;
                       }
          @@ -124,19 +125,23 @@ private boolean hasSqlMapClientImport(List importDeclarati
           
               /**
                * check if any method matches queryForList(String statementName,int start,int size)
          +     * @param node node
          +     * @param data ruleContext
          +     * @param sqlMapFields sqlMapFields
          +     * @throws JaxenException when saxpath fails.
                */
               private void visitPrimaryExpression(ASTPrimaryExpression node, Object data,
          -        Set sqlMapFields) throws JaxenException {
          +                                        Set sqlMapFields) throws JaxenException {
                   List astNames = node.findChildNodesWithXPath(PRIMARY_METHOD_NAME_XPATH);
                   for (Node astName : astNames) {
                       String methodName = astName.getImage();
                       //method name not match
                       if (!(StringUtils.isNotEmpty(methodName) && methodName.contains(
          -                IBATIS_QUERY_FOR_LIST_METHOD_NAME))) {
          +                    IBATIS_QUERY_FOR_LIST_METHOD_NAME))) {
                           continue;
                       }
                       String methodInvokeName = methodName.substring(0,
          -                methodName.indexOf(IBATIS_QUERY_FOR_LIST_METHOD_NAME));
          +                    methodName.indexOf(IBATIS_QUERY_FOR_LIST_METHOD_NAME));
                       //the method caller is empty
                       if (StringUtils.isEmpty(methodInvokeName)) {
                           continue;
          @@ -152,16 +157,16 @@ private void visitPrimaryExpression(ASTPrimaryExpression node, Object data,
                           continue;
                       }
                       boolean firstMethodArgumentString = "java.lang.String".equals(
          -                ((ASTLiteral)(literals.get(0))).getType().getName());
          +                    ((ASTLiteral) (literals.get(0))).getType().getName());
                       boolean secondMethodArgumentInt = "int".equals(
          -                ((ASTLiteral)(literals.get(1))).getType().getName());
          +                    ((ASTLiteral) (literals.get(1))).getType().getName());
                       boolean thirdMethodArgumentInt = "int".equals(
          -                ((ASTLiteral)(literals.get(2))).getType().getName());
          +                    ((ASTLiteral) (literals.get(2))).getType().getName());
                       //if the parameter name and method name all matching, that is a violation of the rules
                       if (firstMethodArgumentString && secondMethodArgumentInt
          -                && thirdMethodArgumentInt) {
          +                    && thirdMethodArgumentInt) {
                           ViolationUtils.addViolationWithPrecisePosition(this, node, data,
          -                    I18nResources.getMessage("java.naming.IbatisMethodQueryForListRule.violation.msg"));
          +                        I18nResources.getMessage("java.naming.IbatisMethodQueryForListRule.violation.msg"));
                       }
           
                   }
          @@ -169,16 +174,18 @@ private void visitPrimaryExpression(ASTPrimaryExpression node, Object data,
           
               /**
                * if the attributes of a class defines the SqlMapClient object,collect these object name
          +     * @param node node
          +     * @return if is SqlMapClientField
                */
               private boolean sqlMapClientField(ASTFieldDeclaration node) {
                   try {
                       List astClassOrInterfaceTypes = node.findChildNodesWithXPath(
          -                "Type/ReferenceType/ClassOrInterfaceType");
          +                    "Type/ReferenceType/ClassOrInterfaceType");
                       //find  the SqlMapClient attribute node, collect these node's parent to sqlMapClientTypeFieldList
                       for (Node astClassOrInterfaceType : astClassOrInterfaceTypes) {
                           String fieldTypeName = astClassOrInterfaceType.getImage();
                           if (SQL_MAP_CLIENT_NAME.equals(fieldTypeName)
          -                    || SQL_MAP_CLIENT_IMPORT_FULL_NAME.equals(fieldTypeName)) {
          +                        || SQL_MAP_CLIENT_IMPORT_FULL_NAME.equals(fieldTypeName)) {
                               return true;
                           }
                       }
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/AvoidApacheBeanUtilsCopyRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/other/AvoidApacheBeanUtilsCopyRule.java
          similarity index 65%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/AvoidApacheBeanUtilsCopyRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/other/AvoidApacheBeanUtilsCopyRule.java
          index 4ad8568de..dd985c19c 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/AvoidApacheBeanUtilsCopyRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/other/AvoidApacheBeanUtilsCopyRule.java
          @@ -13,25 +13,25 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.other;
          -
          -import com.alibaba.p3c.pmd.lang.AbstractXpathRule;
          -import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils;
          +package com.xenoamess.p3c.pmd.lang.java.rule.other;
           
          +import com.xenoamess.p3c.pmd.lang.AbstractAliXpathRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils;
           import net.sourceforge.pmd.lang.ast.Node;
           
           /**
          - * Avoid using *Apache Beanutils* to copy attributes.
          + * Avoid using *Apache BeanUtils* to copy attributes.
            * Note: *Spring BeanUtils* and *Cglib BeanCopier* are recommended to be used, which have better performance.
          - * 
          + *
            * @author keriezhang
            * @date 2016/12/14
            *
            */
          -public class AvoidApacheBeanUtilsCopyRule extends AbstractXpathRule {
          +public class AvoidApacheBeanUtilsCopyRule extends AbstractAliXpathRule {
               private static final String XPATH =
          -            "//PrimaryPrefix/Name[@Image='BeanUtils.copyProperties' and "
          -            + "//ImportDeclaration[@ImportedName='org.apache.commons.beanutils.BeanUtils']]";
          +            "//PrimaryPrefix/Name[(@Image='BeanUtils.copyProperties' and "
          +                    + "//ImportDeclaration[@ImportedName='org.apache.commons.beanutils.BeanUtils']) or "
          +                    + "starts-with(@Image,'org.apache.commons.beanutils.BeanUtils.copyProperties')]";
           
               public AvoidApacheBeanUtilsCopyRule() {
                   setXPath(XPATH);
          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/xenoamess/p3c/pmd/lang/java/rule/other/AvoidDoubleOrFloatEqualCompareRule.java
          similarity index 88%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/AvoidDoubleOrFloatEqualCompareRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/other/AvoidDoubleOrFloatEqualCompareRule.java
          index fffb1cecf..d4ff8151a 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/AvoidDoubleOrFloatEqualCompareRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/other/AvoidDoubleOrFloatEqualCompareRule.java
          @@ -1,7 +1,7 @@
          -package com.alibaba.p3c.pmd.lang.java.rule.other;
          +package com.xenoamess.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 com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils;
           import net.sourceforge.pmd.lang.java.ast.ASTEqualityExpression;
           import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression;
           
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/AvoidMissUseOfMathRandomRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/other/AvoidMissUseOfMathRandomRule.java
          similarity index 67%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/AvoidMissUseOfMathRandomRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/other/AvoidMissUseOfMathRandomRule.java
          index 3d22a7844..03232b636 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/AvoidMissUseOfMathRandomRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/other/AvoidMissUseOfMathRandomRule.java
          @@ -13,11 +13,10 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.other;
          -
          -import com.alibaba.p3c.pmd.lang.AbstractXpathRule;
          -import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils;
          +package com.xenoamess.p3c.pmd.lang.java.rule.other;
           
          +import com.xenoamess.p3c.pmd.lang.AbstractAliXpathRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils;
           import net.sourceforge.pmd.lang.ast.Node;
           
           /**
          @@ -28,13 +27,14 @@
            * @author keriezhang
            * @date 2017/04/14
            */
          -public class AvoidMissUseOfMathRandomRule extends AbstractXpathRule {
          +public class AvoidMissUseOfMathRandomRule extends AbstractAliXpathRule {
           
               private static final String XPATH =
          -        "//PrimaryExpression[./PrimaryPrefix/Name[@Image='Math.random'] and "
          -            + "../../MultiplicativeExpression/PrimaryExpression/PrimaryPrefix/Literal[matches(@Image, '^\\d+$')] and "
          -            + "../../../../../../CastExpression/Type/PrimitiveType[matches(@Image, '^(int|long)$')]"
          -            + "]";
          +            "//PrimaryExpression[./PrimaryPrefix/Name[@Image='Math.random'] and "
          +                    + "../../MultiplicativeExpression/PrimaryExpression/PrimaryPrefix/Literal[matches(@Image, " +
          +                    "'^\\d+$')] and "
          +                    + "../../../../../../CastExpression/Type/PrimitiveType[matches(@Image, '^(int|long)$')]"
          +                    + "]";
           
               public AvoidMissUseOfMathRandomRule() {
                   setXPath(XPATH);
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/AvoidNewDateGetTimeRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/other/AvoidNewDateGetTimeRule.java
          similarity index 58%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/AvoidNewDateGetTimeRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/other/AvoidNewDateGetTimeRule.java
          index 49e72b7b0..61f3bf696 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/AvoidNewDateGetTimeRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/other/AvoidNewDateGetTimeRule.java
          @@ -13,12 +13,11 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -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.ViolationUtils;
          +package com.xenoamess.p3c.pmd.lang.java.rule.other;
           
          +import com.xenoamess.p3c.pmd.I18nResources;
          +import com.xenoamess.p3c.pmd.lang.AbstractAliXpathRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils;
           import net.sourceforge.pmd.lang.ast.Node;
           
           /**
          @@ -27,16 +26,16 @@
            * @author keriezhang
            * @date 2016/12/14
            */
          -public class AvoidNewDateGetTimeRule extends AbstractXpathRule {
          +public class AvoidNewDateGetTimeRule extends AbstractAliXpathRule {
           
               private static final String XPATH =
          -        "//PrimaryExpression"
          -            + "["
          -            + "PrimaryPrefix/AllocationExpression/ClassOrInterfaceType[@Image='Date'] and "
          -            + "PrimaryPrefix/AllocationExpression/Arguments[@ArgumentCount=0] and "
          -            + "PrimarySuffix[@Image='getTime'] and "
          -            + "PrimarySuffix/Arguments[@ArgumentCount=0]"
          -            + "]";
          +            "//PrimaryExpression"
          +                    + "["
          +                    + "PrimaryPrefix/AllocationExpression/ClassOrInterfaceType[@Image='Date'] and "
          +                    + "PrimaryPrefix/AllocationExpression/Arguments[@Size=0] and "
          +                    + "PrimarySuffix[@Image='getTime'] and "
          +                    + "PrimarySuffix/Arguments[@Size=0]"
          +                    + "]";
           
               public AvoidNewDateGetTimeRule() {
                   setXPath(XPATH);
          @@ -45,6 +44,6 @@ public AvoidNewDateGetTimeRule() {
               @Override
               public void addViolation(Object data, Node node, String arg) {
                   ViolationUtils.addViolationWithPrecisePosition(this, node, data,
          -            I18nResources.getMessage("java.other.AvoidNewDateGetTimeRule.violation.msg"));
          +                I18nResources.getMessage("java.other.AvoidNewDateGetTimeRule.violation.msg"));
               }
           }
          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/xenoamess/p3c/pmd/lang/java/rule/other/AvoidPatternCompileInMethodRule.java
          similarity index 66%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/AvoidPatternCompileInMethodRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/other/AvoidPatternCompileInMethodRule.java
          index 12cb1f2a1..a948681be 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/AvoidPatternCompileInMethodRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/other/AvoidPatternCompileInMethodRule.java
          @@ -13,13 +13,12 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -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;
          +package com.xenoamess.p3c.pmd.lang.java.rule.other;
           
          +import com.xenoamess.p3c.pmd.I18nResources;
          +import com.xenoamess.p3c.pmd.lang.AbstractAliXpathRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.VariableUtils;
          +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils;
           import net.sourceforge.pmd.lang.ast.Node;
           import net.sourceforge.pmd.lang.java.ast.ASTLocalVariableDeclaration;
           
          @@ -30,14 +29,14 @@
            * @author keriezhang
            * @date 2016/12/14
            */
          -public class AvoidPatternCompileInMethodRule extends AbstractXpathRule {
          +public class AvoidPatternCompileInMethodRule extends AbstractAliXpathRule {
               /**
                * The parameter of Pattern.compile cannot be a string literal.
                */
               private static final String XPATH = "//MethodDeclaration//PrimaryExpression["
          -        + "PrimaryPrefix/Name[@Image='Pattern.compile'] and "
          -        + "PrimarySuffix/Arguments/ArgumentList/Expression/"
          -        + "PrimaryExpression/PrimaryPrefix/Literal[@StringLiteral='true']]";
          +            + "PrimaryPrefix/Name[@Image='Pattern.compile'] and "
          +            + "PrimarySuffix/Arguments/ArgumentList/Expression/"
          +            + "PrimaryExpression/PrimaryPrefix/Literal[@StringLiteral='true']]";
           
               public AvoidPatternCompileInMethodRule() {
                   setXPath(XPATH);
          @@ -46,13 +45,13 @@ public AvoidPatternCompileInMethodRule() {
               @Override
               public void addViolation(Object data, Node node, String arg) {
                   ASTLocalVariableDeclaration localVariableDeclaration = node.getFirstParentOfType(
          -            ASTLocalVariableDeclaration.class);
          +                ASTLocalVariableDeclaration.class);
                   if (localVariableDeclaration == null) {
                       super.addViolation(data, node, arg);
                   } else {
                       ViolationUtils.addViolationWithPrecisePosition(this, node, data,
          -                I18nResources.getMessage("java.other.AvoidPatternCompileInMethodRule.violation.msg",
          -                    VariableUtils.getVariableName(localVariableDeclaration)));
          +                    I18nResources.getMessage("java.other.AvoidPatternCompileInMethodRule.violation.msg",
          +                            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/xenoamess/p3c/pmd/lang/java/rule/other/MethodTooLongRule.java
          similarity index 84%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/MethodTooLongRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/other/MethodTooLongRule.java
          index 4f4d29a2d..d91fd82c3 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/MethodTooLongRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/other/MethodTooLongRule.java
          @@ -13,18 +13,12 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -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;
          +package com.xenoamess.p3c.pmd.lang.java.rule.other;
           
          +import com.xenoamess.p3c.pmd.I18nResources;
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
          +import com.xenoamess.p3c.pmd.lang.java.rule.util.NodeSortUtils;
          +import com.xenoamess.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;
          @@ -38,6 +32,11 @@
           import net.sourceforge.pmd.lang.java.ast.SingleLineComment;
           import net.sourceforge.pmd.lang.java.ast.Token;
           
          +import java.util.List;
          +import java.util.Map.Entry;
          +import java.util.SortedMap;
          +import java.util.TreeMap;
          +
           /**
            * [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, blank lines,
          @@ -66,19 +65,19 @@ public Object visit(ASTCompilationUnit cUnit, Object data) {
               public Object visit(ASTMethodDeclaration node, Object data) {
                   // Include method modifiers.
                   ASTClassOrInterfaceBodyDeclaration classOrInterfaceBodyDecl =
          -            (ASTClassOrInterfaceBodyDeclaration)node.jjtGetParent();
          +                (ASTClassOrInterfaceBodyDeclaration) node.jjtGetParent();
           
                   int startLine = classOrInterfaceBodyDecl.getBeginLine();
                   int endLine = classOrInterfaceBodyDecl.getEndLine();
           
          -        Node firstChild = classOrInterfaceBodyDecl.jjtGetChild(0);
          +        Node firstChild = classOrInterfaceBodyDecl.getChild(0);
                   // Method has annotation
                   if (firstChild instanceof ASTAnnotation) {
          -            Token firstToken = (Token)classOrInterfaceBodyDecl.jjtGetFirstToken();
          +            Token firstToken = (Token) classOrInterfaceBodyDecl.jjtGetFirstToken();
                       // If annotation is before modifier, exclude the annotation.
                       if (ANNOTATION_PREFIX.equals(firstToken.image)) {
          -                ASTAnnotation annotation = (ASTAnnotation)firstChild;
          -                Token lastToken = (Token)annotation.jjtGetLastToken();
          +                ASTAnnotation annotation = (ASTAnnotation) firstChild;
          +                Token lastToken = (Token) annotation.jjtGetLastToken();
           
                           // First token after annotation. The same line or next line after annotation.
                           Token next = lastToken.next;
          @@ -91,7 +90,7 @@ public Object visit(ASTMethodDeclaration node, Object data) {
           
                   if (endLine - startLine - commentLineCount + 1 > MAX_LINE_COUNT) {
                       ViolationUtils.addViolationWithPrecisePosition(this, node, data,
          -                I18nResources.getMessage("java.other.MethodTooLongRule.violation.msg", node.getName()));
          +                    I18nResources.getMessage("java.other.MethodTooLongRule.violation.msg", node.getName()));
                   }
                   return data;
               }
          @@ -118,8 +117,8 @@ protected SortedMap orderedCommentsAndExpressions(ASTCompilationU
               /**
                * Get number of comment lines
                *
          -     * @param methodDecl
          -     * @return
          +     * @param methodDecl methodDecl node
          +     * @return lineCount
                */
               private int getCommentLineCount(ASTMethodDeclaration methodDecl) {
                   int lineCount = 0;
          @@ -136,12 +135,12 @@ private int getCommentLineCount(ASTMethodDeclaration methodDecl) {
           
                       // value should be either expression or comment.
                       if (value instanceof AbstractJavaNode) {
          -                lastNode = (AbstractJavaNode)value;
          +                lastNode = (AbstractJavaNode) value;
                       } else if (value instanceof FormalComment || value instanceof MultiLineComment) {
          -                Comment comment = (Comment)value;
          +                Comment comment = (Comment) value;
                           lineCount += comment.getEndLine() - comment.getBeginLine() + 1;
                       } else if (value instanceof SingleLineComment) {
          -                SingleLineComment singleLineComment = (SingleLineComment)value;
          +                SingleLineComment singleLineComment = (SingleLineComment) value;
                           // Comment may in the same line with node.
                           if (lastNode == null || singleLineComment.getBeginLine() != lastNode.getBeginLine()) {
                               lineCount += 1;
          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/xenoamess/p3c/pmd/lang/java/rule/other/UseRightCaseForDateFormatRule.java
          similarity index 72%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/UseRightCaseForDateFormatRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/other/UseRightCaseForDateFormatRule.java
          index 68a8e2300..e01c96fff 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/UseRightCaseForDateFormatRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/other/UseRightCaseForDateFormatRule.java
          @@ -1,17 +1,9 @@
          -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;
          +package com.xenoamess.p3c.pmd.lang.java.rule.other;
           
          +import com.xenoamess.p3c.pmd.lang.AbstractAliXpathRule;
           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.
          @@ -33,11 +25,11 @@
            * @author huawen.phw
            * @date 2018/1/9
            */
          -public class UseRightCaseForDateFormatRule extends AbstractXpathRule {
          +public class UseRightCaseForDateFormatRule extends AbstractAliXpathRule {
           
               private static final String NEW_XPATH
          -        = "//AllocationExpression/ClassOrInterfaceType[@Image='SimpleDateFormat']/../Arguments/ArgumentList"
          -        + "/Expression/PrimaryExpression/PrimaryPrefix/*";
          +            = "//AllocationExpression/ClassOrInterfaceType[@Image='SimpleDateFormat']/../Arguments/ArgumentList"
          +            + "/Expression/PrimaryExpression/PrimaryPrefix/*";
               private static final String LOW_CASE_4Y = "yyyy";
               private static final String LOW_CASE_2Y = "yy";
               private static final String START_QUOTE = "\"";
          @@ -54,8 +46,8 @@ public void addViolation(Object data, Node node, String arg) {
               /**
                * 暂只检查4个y和2个y开头的日期格式化字符串参数,不考虑其他类型
                *
          -     * @param argNode
          -     * @param data
          +     * @param argNode argNode
          +     * @param data ruleContext
                */
               private void checkNode(Node argNode, Object data) {
                   String image = "";
          @@ -70,12 +62,12 @@ private void checkNode(Node argNode, Object data) {
                   String lowerCaseTmp = image.toLowerCase();
                   if (!image.startsWith(LOW_CASE_4Y) && lowerCaseTmp.startsWith(LOW_CASE_4Y)) {
                       addViolationWithMessage(data, argNode,
          -                "java.other.UseRightCaseForDateFormatRule.rule.msg",
          -                new Object[] {image});
          +                    "java.other.UseRightCaseForDateFormatRule.rule.msg",
          +                    new Object[]{image});
                   } else if (!image.startsWith(LOW_CASE_2Y) && lowerCaseTmp.startsWith(LOW_CASE_2Y)) {
                       addViolationWithMessage(data, argNode,
          -                "java.other.UseRightCaseForDateFormatRule.rule.msg",
          -                new Object[] {image});
          +                    "java.other.UseRightCaseForDateFormatRule.rule.msg",
          +                    new Object[]{image});
                   } else {
                       //暂不考虑
                   }
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/set/ClassCastExceptionWithSubListToArrayListRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/set/ClassCastExceptionWithSubListToArrayListRule.java
          similarity index 79%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/set/ClassCastExceptionWithSubListToArrayListRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/set/ClassCastExceptionWithSubListToArrayListRule.java
          index e19905923..7b4b2667b 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/set/ClassCastExceptionWithSubListToArrayListRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/set/ClassCastExceptionWithSubListToArrayListRule.java
          @@ -13,17 +13,16 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.set;
          -
          -import java.util.List;
          -
          -import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule;
          +package com.xenoamess.p3c.pmd.lang.java.rule.set;
           
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
           import net.sourceforge.pmd.lang.ast.Node;
           import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
           import net.sourceforge.pmd.lang.java.ast.ASTName;
           import org.jaxen.JaxenException;
           
          +import java.util.List;
          +
           /**
            * [Mandatory] Do not cast subList in class ArrayList, otherwise ClassCastException will be
            * thrown:java.util.RandomAccessSubList
          @@ -35,8 +34,8 @@
           public class ClassCastExceptionWithSubListToArrayListRule extends AbstractAliRule {
           
               private static final String XPATH =
          -        "//CastExpression[Type/ReferenceType/ClassOrInterfaceType[@Image = "
          -            + "\"ArrayList\"]]/PrimaryExpression/PrimaryPrefix/Name[ends-with(@Image,'.subList')]";
          +            "//CastExpression[Type/ReferenceType/ClassOrInterfaceType[@Image = "
          +                    + "\"ArrayList\"]]/PrimaryExpression/PrimaryPrefix/Name[ends-with(@Image,'.subList')]";
           
               @Override
               public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
          @@ -50,8 +49,8 @@ public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
                               continue;
                           }
                           addViolationWithMessage(data, item,
          -                    "java.set.ClassCastExceptionWithSubListToArrayListRule.violation.msg",
          -                    new Object[] {item.getImage()});
          +                        "java.set.ClassCastExceptionWithSubListToArrayListRule.violation.msg",
          +                        new Object[]{item.getImage()});
                       }
                   } catch (JaxenException e) {
                       e.printStackTrace();
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/set/ClassCastExceptionWithToArrayRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/set/ClassCastExceptionWithToArrayRule.java
          similarity index 67%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/set/ClassCastExceptionWithToArrayRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/set/ClassCastExceptionWithToArrayRule.java
          index 53455d41a..b3d886498 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/set/ClassCastExceptionWithToArrayRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/set/ClassCastExceptionWithToArrayRule.java
          @@ -13,12 +13,9 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.set;
          -
          -import java.util.List;
          -
          -import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule;
          +package com.xenoamess.p3c.pmd.lang.java.rule.set;
           
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
           import net.sourceforge.pmd.lang.ast.Node;
           import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
           import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression;
          @@ -26,6 +23,8 @@
           import net.sourceforge.pmd.lang.java.ast.ASTPrimarySuffix;
           import org.jaxen.JaxenException;
           
          +import java.util.List;
          +
           /**
            * [Mandatory] Do not use toArray method without arguments. Since the return type is Object[], ClassCastException will
            * be thrown when casting it to a different array type。
          @@ -36,7 +35,7 @@
           public class ClassCastExceptionWithToArrayRule extends AbstractAliRule {
           
               private static final String XPATH
          -        = "//CastExpression[Type/ReferenceType/ClassOrInterfaceType[@Image !=\"Object\"]]/PrimaryExpression";
          +            = "//CastExpression[Type/ReferenceType/ClassOrInterfaceType[@Image !=\"Object\"]]/PrimaryExpression";
           
               @Override
               public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
          @@ -49,30 +48,30 @@ public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
                           if (!(item instanceof ASTPrimaryExpression)) {
                               continue;
                           }
          -                ASTPrimaryExpression primaryExpression = (ASTPrimaryExpression)item;
          -                List primaryPrefixs =
          -                    primaryExpression.findChildrenOfType(ASTPrimaryPrefix.class);
          -                List primarySuffixs =
          -                    primaryExpression.findChildrenOfType(ASTPrimarySuffix.class);
          -                if (primaryPrefixs == null || primarySuffixs == null || primaryPrefixs.isEmpty()
          -                    || primarySuffixs.isEmpty()) {
          +                ASTPrimaryExpression primaryExpression = (ASTPrimaryExpression) item;
          +                List primaryPrefixes =
          +                        primaryExpression.findChildrenOfType(ASTPrimaryPrefix.class);
          +                List primarySuffixes =
          +                        primaryExpression.findChildrenOfType(ASTPrimarySuffix.class);
          +                if (primaryPrefixes == null || primarySuffixes == null || primaryPrefixes.isEmpty()
          +                        || primarySuffixes.isEmpty()) {
                               continue;
                           }
          -                ASTPrimaryPrefix prefix = primaryPrefixs.get(0);
          -                ASTPrimarySuffix suffix = primarySuffixs.get(0);
          -                if (prefix.jjtGetNumChildren() == 0) {
          +                ASTPrimaryPrefix prefix = primaryPrefixes.get(0);
          +                ASTPrimarySuffix suffix = primarySuffixes.get(0);
          +                if (prefix.getNumChildren() == 0) {
                               continue;
                           }
          -                Node prefixChildNode = prefix.jjtGetChild(0);
          +                Node prefixChildNode = prefix.getChild(0);
                           String childName = prefixChildNode.getImage();
                           if (childName == null) {
                               continue;
                           }
                           if (childName.endsWith(".toArray") && suffix.getArgumentCount() == 0
          -                    && primarySuffixs.size() == 1) {
          +                        && primarySuffixes.size() == 1) {
                               addViolationWithMessage(data, item,
          -                        "java.set.ClassCastExceptionWithToArrayRule.violation.msg",
          -                        new Object[] {childName});
          +                            "java.set.ClassCastExceptionWithToArrayRule.violation.msg",
          +                            new Object[]{childName});
                           }
                       }
           
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/set/CollectionInitShouldAssignCapacityRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/set/CollectionInitShouldAssignCapacityRule.java
          similarity index 70%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/set/CollectionInitShouldAssignCapacityRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/set/CollectionInitShouldAssignCapacityRule.java
          index 4b3c7398f..8922d1ef8 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/set/CollectionInitShouldAssignCapacityRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/set/CollectionInitShouldAssignCapacityRule.java
          @@ -13,19 +13,18 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.set;
          -
          -import java.util.List;
          -
          -import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule;
          -import com.alibaba.p3c.pmd.lang.java.util.namelist.NameListConfig;
          +package com.xenoamess.p3c.pmd.lang.java.rule.set;
           
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.namelist.NameListConfig;
           import net.sourceforge.pmd.lang.ast.Node;
           import net.sourceforge.pmd.lang.java.ast.ASTArguments;
           import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
           import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
           import org.jaxen.JaxenException;
           
          +import java.util.List;
          +
           /**
            * [Recommended] Set a size when initializing a collection if possible.
            *
          @@ -36,15 +35,20 @@ public class CollectionInitShouldAssignCapacityRule extends AbstractAliRule {
           
               /**
                * Black List,will increase ArrayList, HashSet etc follow-up
          +     * @return CollectionInitShouldAssignCapacityRule COLLECTION_TYPE
                */
          -    private final static List COLLECTION_LIST = NameListConfig.NAME_LIST_SERVICE
          -        .getNameList(CollectionInitShouldAssignCapacityRule.class.getSimpleName(), "COLLECTION_TYPE");
          +    private static List getCollectionList() {
          +        return NameListConfig.getNameListService().getNameList(
          +                CollectionInitShouldAssignCapacityRule.class.getSimpleName(),
          +                "COLLECTION_TYPE"
          +        );
          +    }
           
               @Override
               public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
                   try {
                       // find Collection initialization
          -            for (String collectionType : COLLECTION_LIST) {
          +            for (String collectionType : getCollectionList()) {
                           visitByCollections(node, data, collectionType);
                       }
                   } catch (JaxenException e) {
          @@ -54,9 +58,9 @@ public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
               }
           
               private void visitByCollections(ASTClassOrInterfaceDeclaration node, Object data, String collectionType)
          -        throws JaxenException {
          +            throws JaxenException {
                   String collectionArgXpath =
          -            "//AllocationExpression/ClassOrInterfaceType[@Image='" + collectionType + "']/../Arguments";
          +                "//AllocationExpression/ClassOrInterfaceType[@Image='" + collectionType + "']/../Arguments";
                   List argumentsNodes = node.findChildNodesWithXPath(collectionArgXpath);
           
                   for (Node argNode : argumentsNodes) {
          @@ -67,13 +71,13 @@ private void visitByCollections(ASTClassOrInterfaceDeclaration node, Object data
                       if (argNode.getFirstParentOfType(ASTMethodDeclaration.class) == null) {
                           continue;
                       }
          -            ASTArguments argumentNode = (ASTArguments)argNode;
          -            Integer count = argumentNode.getArgumentCount();
          +            ASTArguments argumentNode = (ASTArguments) argNode;
          +            int count = argumentNode.size();
                       // judge whether parameters have  initial size
                       if (count == 0) {
                           addViolationWithMessage(data, argNode,
          -                    "java.set.CollectionInitShouldAssignCapacityRule.violation.msg",
          -                    new Object[] {collectionType});
          +                        "java.set.CollectionInitShouldAssignCapacityRule.violation.msg",
          +                        new Object[]{collectionType});
                       }
                   }
               }
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/set/ConcurrentExceptionWithModifyOriginSubListRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/set/ConcurrentExceptionWithModifyOriginSubListRule.java
          similarity index 68%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/set/ConcurrentExceptionWithModifyOriginSubListRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/set/ConcurrentExceptionWithModifyOriginSubListRule.java
          index 3aeaf647b..a71459115 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/set/ConcurrentExceptionWithModifyOriginSubListRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/set/ConcurrentExceptionWithModifyOriginSubListRule.java
          @@ -13,18 +13,17 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.set;
          -
          -import java.util.List;
          -
          -import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule;
          +package com.xenoamess.p3c.pmd.lang.java.rule.set;
           
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
           import net.sourceforge.pmd.lang.ast.Node;
           import net.sourceforge.pmd.lang.java.ast.ASTBlock;
           import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
           import net.sourceforge.pmd.lang.java.ast.ASTName;
           import org.jaxen.JaxenException;
           
          +import java.util.List;
          +
           /**
            * [Mandatory] When using subList, be careful to modify the size of original list. It might cause
            * ConcurrentModificationException when performing traversing, adding or deleting on the subList.
          @@ -34,14 +33,14 @@
            */
           public class ConcurrentExceptionWithModifyOriginSubListRule extends AbstractAliRule {
           
          -    private final static String ADD = ".add";
          -    private final static String REMOVE = ".remove";
          -    private final static String CLEAR = ".clear";
          -    private final static String XPATH
          -        = "//VariableDeclarator[../Type/ReferenceType/ClassOrInterfaceType[@Image='List']]/VariableInitializer"
          -        + "/Expression/PrimaryExpression/PrimaryPrefix/Name[ends-with(@Image,'.subList')]";
          -    private final static String CHILD_XPATH
          -        = "BlockStatement/Statement/StatementExpression/PrimaryExpression/PrimaryPrefix/Name";
          +    private static final String ADD = ".add";
          +    private static final String REMOVE = ".remove";
          +    private static final String CLEAR = ".clear";
          +    private static final String XPATH
          +            = "//VariableDeclarator[../Type/ReferenceType/ClassOrInterfaceType[@Image='List']]/VariableInitializer"
          +            + "/Expression/PrimaryExpression/PrimaryPrefix/Name[ends-with(@Image,'.subList')]";
          +    private static final String CHILD_XPATH
          +            = "BlockStatement/Statement/StatementExpression/PrimaryExpression/PrimaryPrefix/Name";
           
               @Override
               public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
          @@ -68,8 +67,8 @@ public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
                               }
                               if (checkBlockNodesValid(valName, blockItem)) {
                                   addViolationWithMessage(data, blockItem,
          -                            "java.set.ConcurrentExceptionWithModifyOriginSubListRule.violation.msg",
          -                            new Object[] {blockItem.getImage()});
          +                                "java.set.ConcurrentExceptionWithModifyOriginSubListRule.violation.msg",
          +                                new Object[]{blockItem.getImage()});
                               }
                           }
           
          @@ -83,27 +82,24 @@ public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
               /**
                * Find subList original variable
                *
          -     * @param image
          -     * @return
          +     * @param image image
          +     * @return image.substring(0, image.indexOf ( " . "))
                */
          -    private String getBeforeSubListVal(String image) {
          +    private static String getBeforeSubListVal(String image) {
                   return image == null ? null : image.substring(0, image.indexOf("."));
               }
           
               /**
                * Only to find out whether there is any violation within the scope of the  method
                *
          -     * @param variableName
          -     * @param item
          -     * @return
          -     * @throws JaxenException
          +     * @param variableName variableName
          +     * @param item node
          +     * @return ifCheckBlockNodesValid
                */
          -    private boolean checkBlockNodesValid(String variableName, Node item) {
          +    private static boolean checkBlockNodesValid(String variableName, Node item) {
                   if (item instanceof ASTName) {
                       String name = item.getImage();
          -            if (judgeName(name, variableName)) {
          -                return true;
          -            }
          +            return judgeName(name, variableName);
                   }
                   return false;
               }
          @@ -111,12 +107,12 @@ private boolean checkBlockNodesValid(String variableName, Node item) {
               /**
                * judge name equals to  t.add / t.remove / t.clear
                *
          -     * @param name
          -     * @param variableName
          -     * @return
          +     * @param name name
          +     * @param variableName variableName
          +     * @return if name
                */
          -    private boolean judgeName(String name, String variableName) {
          +    private static boolean judgeName(String name, String variableName) {
                   return name.equals(variableName + ADD) || name.equals(variableName + REMOVE)
          -            || name.equals(variableName + CLEAR);
          +                || name.equals(variableName + CLEAR);
               }
           }
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/set/DontModifyInForeachCircleRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/set/DontModifyInForeachCircleRule.java
          similarity index 78%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/set/DontModifyInForeachCircleRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/set/DontModifyInForeachCircleRule.java
          index 7e09893cc..12cd6ce30 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/set/DontModifyInForeachCircleRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/set/DontModifyInForeachCircleRule.java
          @@ -13,18 +13,17 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.set;
          -
          -import java.util.List;
          -
          -import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule;
          +package com.xenoamess.p3c.pmd.lang.java.rule.set;
           
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
           import net.sourceforge.pmd.lang.ast.Node;
           import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
           import net.sourceforge.pmd.lang.java.ast.ASTForStatement;
           import net.sourceforge.pmd.lang.java.ast.ASTName;
           import org.jaxen.JaxenException;
           
          +import java.util.List;
          +
           /**
            * [Mandatory] Do not remove or add elements to a collection in a foreach loop. Please use Iterator to remove an item.
            * Iterator object should be synchronized when executing concurrent operations.
          @@ -34,12 +33,12 @@
            */
           public class DontModifyInForeachCircleRule extends AbstractAliRule {
           
          -    private final static String ADD = ".add";
          -    private final static String REMOVE = ".remove";
          -    private final static String CLEAR = ".clear";
          -    private final static String XPATH = "//ForStatement/Expression/PrimaryExpression/PrimaryPrefix/Name";
          -    private final static String CHILD_XPATH
          -        = "Statement/Block/BlockStatement/Statement/StatementExpression/PrimaryExpression/PrimaryPrefix/Name";
          +    private static final String ADD = ".add";
          +    private static final String REMOVE = ".remove";
          +    private static final String CLEAR = ".clear";
          +    private static final String XPATH = "//ForStatement/Expression/PrimaryExpression/PrimaryPrefix/Name";
          +    private static final String CHILD_XPATH
          +            = "Statement/Block/BlockStatement/Statement/StatementExpression/PrimaryExpression/PrimaryPrefix/Name";
           
               @Override
               public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
          @@ -64,8 +63,8 @@ public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
                               }
                               if (judgeName(blockItem.getImage(), variableName)) {
                                   addViolationWithMessage(data, blockItem,
          -                            "java.set.DontModifyInForeachCircleRule.violation.msg",
          -                            new Object[] {blockItem.getImage()});
          +                                "java.set.DontModifyInForeachCircleRule.violation.msg",
          +                                new Object[]{blockItem.getImage()});
                               }
                           }
                       }
          @@ -77,7 +76,7 @@ public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
           
               private boolean judgeName(String name, String variableName) {
                   return name != null && (name.equals(variableName + ADD) ||
          -            name.equals(variableName + REMOVE) || name.equals(variableName + CLEAR));
          +                name.equals(variableName + REMOVE) || name.equals(variableName + CLEAR));
               }
           
           }
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/set/UnsupportedExceptionWithModifyAsListRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/set/UnsupportedExceptionWithModifyAsListRule.java
          similarity index 71%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/set/UnsupportedExceptionWithModifyAsListRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/set/UnsupportedExceptionWithModifyAsListRule.java
          index 17f48f328..354ffed88 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/set/UnsupportedExceptionWithModifyAsListRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/set/UnsupportedExceptionWithModifyAsListRule.java
          @@ -13,12 +13,9 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.set;
          -
          -import java.util.List;
          -
          -import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule;
          +package com.xenoamess.p3c.pmd.lang.java.rule.set;
           
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
           import net.sourceforge.pmd.lang.ast.Node;
           import net.sourceforge.pmd.lang.java.ast.ASTBlock;
           import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
          @@ -27,6 +24,8 @@
           import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
           import org.jaxen.JaxenException;
           
          +import java.util.List;
          +
           /**
            * [Mandatory] Do not use methods which will modify the list after using Arrays.asList to convert array to list,
            * otherwise methods like add/remove/clear will throw UnsupportedOperationException.
          @@ -36,14 +35,14 @@
            */
           public class UnsupportedExceptionWithModifyAsListRule extends AbstractAliRule {
           
          -    private final static String ADD = ".add";
          -    private final static String REMOVE = ".remove";
          -    private final static String CLEAR = ".clear";
          -    private final static String XPATH
          -        = "//VariableDeclarator[../Type/ReferenceType/ClassOrInterfaceType[@Image='List']]/VariableInitializer"
          -        + "/Expression/PrimaryExpression/PrimaryPrefix/Name[@Image='Arrays.asList']";
          -    private final static String CHILD_XPATH
          -        = "BlockStatement/Statement/StatementExpression/PrimaryExpression/PrimaryPrefix/Name";
          +    private static final String ADD = ".add";
          +    private static final String REMOVE = ".remove";
          +    private static final String CLEAR = ".clear";
          +    private static final String XPATH
          +            = "//VariableDeclarator[../Type/ReferenceType/ClassOrInterfaceType[@Image='List']]/VariableInitializer"
          +            + "/Expression/PrimaryExpression/PrimaryPrefix/Name[@Image='Arrays.asList']";
          +    private static final String CHILD_XPATH
          +            = "BlockStatement/Statement/StatementExpression/PrimaryExpression/PrimaryPrefix/Name";
           
               @Override
               public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
          @@ -58,13 +57,13 @@ public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
                               continue;
                           }
                           List parents =
          -                    item.getParentsOfType(ASTVariableDeclarator.class);
          +                        item.getParentsOfType(ASTVariableDeclarator.class);
                           if (parents == null || parents.size() == 0 || parents.size() > 1) {
                               continue;
                           }
                           ASTVariableDeclarator declarator = parents.get(0);
                           ASTVariableDeclaratorId variableName =
          -                    declarator.getFirstChildOfType(ASTVariableDeclaratorId.class);
          +                        declarator.getFirstChildOfType(ASTVariableDeclaratorId.class);
           
                           String valName = variableName.getImage();
                           // find Variable scope code block
          @@ -73,15 +72,15 @@ public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
                               continue;
                           }
                           List blockNodes = blockNode.findChildNodesWithXPath(CHILD_XPATH);
          -                // variable.add .removed is forbbiden.
          +                // variable.add .removed is forbidden.
                           for (Node blockItem : blockNodes) {
                               if (blockItem.getBeginLine() < item.getBeginLine()) {
                                   continue;
                               }
                               if (checkBlockNodesValid(valName, blockItem)) {
                                   addViolationWithMessage(data, blockItem,
          -                            "java.set.UnsupportedExceptionWithModifyAsListRule.violation.msg",
          -                            new Object[] {blockItem.getImage()});
          +                                "java.set.UnsupportedExceptionWithModifyAsListRule.violation.msg",
          +                                new Object[]{blockItem.getImage()});
                               }
                           }
           
          @@ -95,31 +94,28 @@ public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
               /**
                * Only to find out whether there is any violation within the scope of the corresponding method
                *
          -     * @param variableName
          -     * @param item
          -     * @return
          -     * @throws JaxenException
          +     * @param variableName variableName
          +     * @param item node
          +     * @return ifCheckBlockNodesValid
                */
               private boolean checkBlockNodesValid(String variableName, Node item) {
                   if (item instanceof ASTName) {
                       String name = item.getImage();
          -            if (judgeName(name, variableName)) {
          -                return true;
          -            }
          +            return judgeName(name, variableName);
                   }
                   return false;
               }
           
               /**
          -     * judge name equels t.add t.remove t.clear
          +     * judge name equals t.add t.remove t.clear
                *
          -     * @param name
          -     * @param variableName
          -     * @return
          +     * @param name name
          +     * @param variableName variableName
          +     * @return if name suits
                */
               private boolean judgeName(String name, String variableName) {
                   return name.equals(variableName + ADD) || name.equals(variableName + REMOVE)
          -            || name.equals(variableName + CLEAR);
          +                || name.equals(variableName + CLEAR);
               }
           
           }
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/util/NodeSortUtils.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/util/NodeSortUtils.java
          similarity index 96%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/util/NodeSortUtils.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/util/NodeSortUtils.java
          index 42b0f9315..95f5a8ee2 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/util/NodeSortUtils.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/util/NodeSortUtils.java
          @@ -13,13 +13,13 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.util;
          +package com.xenoamess.p3c.pmd.lang.java.rule.util;
          +
          +import net.sourceforge.pmd.lang.ast.Node;
           
           import java.util.List;
           import java.util.SortedMap;
           
          -import net.sourceforge.pmd.lang.ast.Node;
          -
           /**
            *
            * @author keriezhang
          @@ -30,7 +30,7 @@ public class NodeSortUtils {
           
               /**
                * add node to SortedMap with sequence to determine comment location
          -     * 
          +     *
                * @param map sorted map
                * @param nodes nodes
                */
          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/xenoamess/p3c/pmd/lang/java/rule/util/NodeUtils.java
          similarity index 83%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/util/NodeUtils.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/util/NodeUtils.java
          index 2582e59c2..a521a95fc 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/util/NodeUtils.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/util/NodeUtils.java
          @@ -13,9 +13,7 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.util;
          -
          -import java.util.concurrent.locks.Lock;
          +package com.xenoamess.p3c.pmd.lang.java.rule.util;
           
           import net.sourceforge.pmd.lang.ast.Node;
           import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration;
          @@ -26,6 +24,8 @@
           import net.sourceforge.pmd.lang.java.ast.Token;
           import net.sourceforge.pmd.lang.java.typeresolution.TypeHelper;
           
          +import java.util.concurrent.locks.Lock;
          +
           /**
            * @author caikang
            * @date 2016/11/16
          @@ -42,9 +42,9 @@ public static boolean isParentOrSelf(Node descendant, Node ancestor) {
                   if (descendant == null || ancestor == null) {
                       return false;
                   }
          -        Node parent = descendant.jjtGetParent();
          +        Node parent = descendant.getParent();
                   while (parent != ancestor && parent != null) {
          -            parent = parent.jjtGetParent();
          +            parent = parent.getParent();
                   }
                   return parent == ancestor;
               }
          @@ -57,13 +57,13 @@ public static boolean isParentOrSelf(Node descendant, Node ancestor) {
                */
               public static boolean isWrapperType(ASTPrimaryExpression expression) {
                   return TypeHelper.isA(expression, Integer.class)
          -            || TypeHelper.isA(expression, Long.class)
          -            || TypeHelper.isA(expression, Boolean.class)
          -            || TypeHelper.isA(expression, Byte.class)
          -            || TypeHelper.isA(expression, Double.class)
          -            || TypeHelper.isA(expression, Short.class)
          -            || TypeHelper.isA(expression, Float.class)
          -            || TypeHelper.isA(expression, Character.class);
          +                || TypeHelper.isA(expression, Long.class)
          +                || TypeHelper.isA(expression, Boolean.class)
          +                || TypeHelper.isA(expression, Byte.class)
          +                || TypeHelper.isA(expression, Double.class)
          +                || TypeHelper.isA(expression, Short.class)
          +                || TypeHelper.isA(expression, Float.class)
          +                || TypeHelper.isA(expression, Character.class);
               }
           
               public static boolean isConstant(ASTFieldDeclaration field) {
          @@ -87,7 +87,7 @@ private static boolean isLockTypeAndMethod(ASTStatementExpression statementExpre
                   if (name == null || name.getType() == null || !Lock.class.isAssignableFrom(name.getType())) {
                       return false;
                   }
          -        Token token = (Token)name.jjtGetLastToken();
          +        Token token = (Token) name.jjtGetLastToken();
                   return methodName.equals(token.image);
               }
           
          @@ -95,7 +95,7 @@ public static boolean isLockNode(Node node) {
                   if (!(node instanceof ASTStatementExpression)) {
                       return false;
                   }
          -        ASTStatementExpression statementExpression = (ASTStatementExpression)node;
          +        ASTStatementExpression statementExpression = (ASTStatementExpression) node;
                   return isLockStatementExpression(statementExpression);
               }
           }
          diff --git a/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/xenoamess/additional/EqualsHashCodeRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/xenoamess/additional/EqualsHashCodeRule.java
          new file mode 100644
          index 000000000..36d284d36
          --- /dev/null
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/xenoamess/additional/EqualsHashCodeRule.java
          @@ -0,0 +1,53 @@
          +package com.xenoamess.p3c.pmd.lang.java.rule.xenoamess.additional;
          +
          +/*
          + * 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.
          + */
          +
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
          +import net.sourceforge.pmd.lang.ast.Node;
          +import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
          +import org.jaxen.JaxenException;
          +
          +import java.util.List;
          +
          +/**
          + * [Mandatory] Equals method must be with hashCode() method.
          + *
          + * @author leonard99559
          + * @date 2019/10/16
          + */
          +public class EqualsHashCodeRule extends AbstractAliRule {
          +
          +    @Override
          +    public Object visit(ASTCompilationUnit rootNode, Object data) {
          +
          +        try {
          +            List nodeList = rootNode.findChildNodesWithXPath(
          +                    "//ClassOrInterfaceDeclaration[@Abstract='false']"
          +                            + "//ClassOrInterfaceBodyDeclaration[./Annotation[@AnnotationName = 'Override']]"
          +                            + "//MethodDeclaration[@Name = 'hashCode' or @Name = 'equals']"
          +            );
          +            if (nodeList.size() == 1) {
          +                addViolationWithMessage(data, nodeList.get(0),
          +                        "java.set.EqualsHashCodeRule.rule.msg");
          +            }
          +        } catch (JaxenException e) {
          +            e.printStackTrace();
          +        }
          +        return super.visit(rootNode, data);
          +    }
          +
          +}
          diff --git a/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/xenoamess/additional/SneakyThrowsWithoutExceptionTypeRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/xenoamess/additional/SneakyThrowsWithoutExceptionTypeRule.java
          new file mode 100644
          index 000000000..6a89991db
          --- /dev/null
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/xenoamess/additional/SneakyThrowsWithoutExceptionTypeRule.java
          @@ -0,0 +1,47 @@
          +package com.xenoamess.p3c.pmd.lang.java.rule.xenoamess.additional;
          +
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule;
          +import net.sourceforge.pmd.lang.ast.Node;
          +import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
          +import org.jaxen.JaxenException;
          +
          +import java.util.Collections;
          +import java.util.List;
          +
          +/**
          + * [Mandatory] SneakyThrow must specify what Exception type it can sneak.
          + *
          + * @author XenoAmess
          + * @date 2021/1/03
          + */
          +public class SneakyThrowsWithoutExceptionTypeRule extends AbstractAliRule {
          +
          +    @Override
          +    public Object visit(ASTCompilationUnit rootNode, Object data) {
          +
          +        List nodeList = Collections.emptyList();
          +        try {
          +            nodeList = rootNode.findChildNodesWithXPath(
          +                    "//ClassOrInterfaceBodyDeclaration"
          +                            + "[./Annotation"
          +                            + "["
          +                            + "(@AnnotationName = 'SneakyThrows' or @AnnotationName = 'lombok.SneakyThrows')"
          +                            + " and"
          +                            + " not((.//MemberValuePair/@Image = 'value') or (./SingleMemberAnnotation))"
          +                            + "]"
          +                            + "]"
          +            );
          +        } catch (JaxenException e) {
          +            e.printStackTrace();
          +        }
          +        for (Node node : nodeList) {
          +            addViolationWithMessage(
          +                    data,
          +                    node,
          +                    "java.xenoamess.additional.SneakyThrowsWithoutExceptionTypeRule.rule.msg"
          +            );
          +        }
          +        return super.visit(rootNode, data);
          +    }
          +
          +}
          diff --git a/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/xenoamess/deprecated/VarargsParameterRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/xenoamess/deprecated/VarargsParameterRule.java
          new file mode 100644
          index 000000000..9f481eb4f
          --- /dev/null
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/rule/xenoamess/deprecated/VarargsParameterRule.java
          @@ -0,0 +1,45 @@
          +package com.xenoamess.p3c.pmd.lang.java.rule.xenoamess.deprecated;
          +
          +/*
          + * 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.
          + */
          +
          +import com.xenoamess.p3c.pmd.I18nResources;
          +import com.xenoamess.p3c.pmd.lang.AbstractAliXpathRule;
          +import com.xenoamess.p3c.pmd.lang.java.util.ViolationUtils;
          +import net.sourceforge.pmd.lang.ast.Node;
          +
          +/**
          + * [Mandatory]
          + *
          + * @author leonard99559
          + * @date 2019/10/16
          + */
          +@Deprecated
          +public class VarargsParameterRule extends AbstractAliXpathRule {
          +    private static final String XPATH = "//FormalParameter[@Varargs = 'true' and ./Type[@TypeImage = 'Object']]";
          +
          +    public VarargsParameterRule() {
          +        setXPath(XPATH);
          +    }
          +
          +    @Override
          +    public void addViolation(Object data, Node node, String arg) {
          +        ViolationUtils.addViolationWithPrecisePosition(this, node, data,
          +                I18nResources.getMessage("java.oop.VarargsParameterRule.rule.msg",
          +                        node.getImage()));
          +    }
          +
          +}
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/GeneratedCodeUtils.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/GeneratedCodeUtils.java
          similarity index 93%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/GeneratedCodeUtils.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/GeneratedCodeUtils.java
          index 69c5a5309..140fffed5 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/GeneratedCodeUtils.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/GeneratedCodeUtils.java
          @@ -13,13 +13,13 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.util;
          -
          -import java.util.List;
          +package com.xenoamess.p3c.pmd.lang.java.util;
           
           import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
           import net.sourceforge.pmd.lang.java.ast.ASTImportDeclaration;
           
          +import java.util.List;
          +
           /**
            * @author caikang
            * @date 2017/06/21
          @@ -31,7 +31,7 @@ public class GeneratedCodeUtils {
           
               public static boolean isGenerated(ASTCompilationUnit compilationUnit) {
                   List importDeclarationList
          -            = compilationUnit.findChildrenOfType(ASTImportDeclaration.class);
          +                = compilationUnit.findChildrenOfType(ASTImportDeclaration.class);
                   if (importDeclarationList.isEmpty()) {
                       return false;
                   }
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/NumberConstants.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/NumberConstants.java
          similarity index 86%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/NumberConstants.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/NumberConstants.java
          index 8316260e8..941b9279e 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/NumberConstants.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/NumberConstants.java
          @@ -13,7 +13,7 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.util;
          +package com.xenoamess.p3c.pmd.lang.java.util;
           
           /**
            * @author caikang
          @@ -21,8 +21,8 @@
            */
           public final class NumberConstants {
               private NumberConstants() {
          -        throw new AssertionError("com.alibaba.p3c.pmd.lang.java.util.NumberConstants"
          -            + " instances for you!");
          +        throw new AssertionError("NumberConstants"
          +                + " instances for you!");
               }
           
               public static final int INTEGER_SIZE_OR_LENGTH_0 = 0;
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/PojoUtils.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/PojoUtils.java
          similarity index 77%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/PojoUtils.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/PojoUtils.java
          index 586a7a48b..d0defba3d 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/PojoUtils.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/PojoUtils.java
          @@ -13,14 +13,13 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.util;
          -
          -import java.util.List;
          -
          -import com.alibaba.p3c.pmd.lang.java.util.namelist.NameListConfig;
          +package com.xenoamess.p3c.pmd.lang.java.util;
           
          +import com.xenoamess.p3c.pmd.lang.java.util.namelist.NameListConfig;
           import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
           
          +import java.util.List;
          +
           /**
            * POJO Utils
            *
          @@ -28,8 +27,9 @@
            * @date 2016/11/25
            */
           public class PojoUtils {
          -    private static final List POJO_SUFFIX_SET =
          -        NameListConfig.NAME_LIST_SERVICE.getNameList("PojoMustOverrideToStringRule", "POJO_SUFFIX_SET");
          +    private static List getPojoSuffixSet() {
          +        return NameListConfig.getNameListService().getNameList("PojoMustOverrideToStringRule", "POJO_SUFFIX_SET");
          +    }
           
               private PojoUtils() {
               }
          @@ -38,7 +38,7 @@ public static boolean isPojo(String klass) {
                   if (klass == null) {
                       return false;
                   }
          -        for (String suffix : POJO_SUFFIX_SET) {
          +        for (String suffix : getPojoSuffixSet()) {
                       if (klass.endsWith(suffix)) {
                           return true;
                       }
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/SpiLoader.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/SpiLoader.java
          similarity index 81%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/SpiLoader.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/SpiLoader.java
          index e6f4f6659..c81aff0fb 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/SpiLoader.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/SpiLoader.java
          @@ -13,23 +13,23 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.util;
          +package com.xenoamess.p3c.pmd.lang.java.util;
          +
          +import com.xenoamess.p3c.pmd.lang.java.util.namelist.NameListConfig;
           
           import java.util.ServiceLoader;
           import java.util.concurrent.ConcurrentHashMap;
           
          -import com.alibaba.p3c.pmd.lang.java.util.namelist.NameListConfig;
          -
           /**
            * @author changle.lq
            * @date 2017/04/01
            */
           public class SpiLoader {
          -    private final static ConcurrentHashMap, Object> INSTANCE_CACHE = new ConcurrentHashMap, Object>();
          +    private static final ConcurrentHashMap, Object> INSTANCE_CACHE = new ConcurrentHashMap<>();
           
               @SuppressWarnings("unchecked")
               public static  T getInstance(Class classType) {
          -        T instance = (T)INSTANCE_CACHE.get(classType);
          +        T instance = (T) INSTANCE_CACHE.get(classType);
           
                   if (instance != null) {
                       return instance;
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/StringAndCharConstants.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/StringAndCharConstants.java
          similarity index 79%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/StringAndCharConstants.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/StringAndCharConstants.java
          index 6b0303dc3..46e3dc3d0 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/StringAndCharConstants.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/StringAndCharConstants.java
          @@ -13,16 +13,16 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.util;
          +package com.xenoamess.p3c.pmd.lang.java.util;
           
           /**
            * @author caikang
            * @date 2017/03/28
            */
           public final class StringAndCharConstants {
          -    private StringAndCharConstants(){
          -        throw new AssertionError("com.alibaba.p3c.pmd.lang.java.util.StringAndCharConstants"
          -            + " instances for you!");
          +    private StringAndCharConstants() {
          +        throw new AssertionError("StringAndCharConstants"
          +                + " instances for you!");
               }
           
               public static final char DOT = '.';
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/VariableUtils.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/VariableUtils.java
          similarity index 91%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/VariableUtils.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/VariableUtils.java
          index 494ee7732..60e784e30 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/VariableUtils.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/VariableUtils.java
          @@ -1,4 +1,4 @@
          -package com.alibaba.p3c.pmd.lang.java.util;
          +package com.xenoamess.p3c.pmd.lang.java.util;
           
           import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
           import net.sourceforge.pmd.lang.java.ast.AbstractJavaAccessNode;
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/ViolationUtils.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/ViolationUtils.java
          similarity index 50%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/ViolationUtils.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/ViolationUtils.java
          index 49aed7430..c8335f638 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/ViolationUtils.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/ViolationUtils.java
          @@ -13,14 +13,20 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.util;
          +package com.xenoamess.p3c.pmd.lang.java.util;
           
          +import com.xenoamess.p3c.pmd.lang.java.util.namelist.NameListConfig;
           import net.sourceforge.pmd.lang.ast.Node;
          +import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
           import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration;
           import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
           import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclarator;
           import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
          +import net.sourceforge.pmd.lang.java.symboltable.ClassScope;
           import net.sourceforge.pmd.lang.rule.AbstractRule;
          +import net.sourceforge.pmd.lang.symboltable.Scope;
          +import net.sourceforge.pmd.lang.symboltable.ScopedNode;
          +import org.jetbrains.annotations.Nullable;
           
           /**
            * @author caikang
          @@ -32,7 +38,11 @@ public static void addViolationWithPrecisePosition(AbstractRule rule, Node node,
               }
           
               public static void addViolationWithPrecisePosition(AbstractRule rule, Node node, Object data,
          -        String message) {
          +                                                       String message) {
          +        if (shouldIgnoreViolation(rule.getClass(), node)) {
          +            return;
          +        }
          +
                   if (node instanceof ASTFieldDeclaration) {
                       ASTVariableDeclaratorId variableDeclaratorId = node.getFirstDescendantOfType(ASTVariableDeclaratorId.class);
                       addViolation(rule, variableDeclaratorId, data, message);
          @@ -53,4 +63,48 @@ private static void addViolation(AbstractRule rule, Node node, Object data, Stri
                       rule.addViolationWithMessage(data, node, message);
                   }
               }
          +
          +    public static boolean shouldIgnoreViolation(Class ruleClass, Node node) {
          +        if (NameListConfig.getNameListService().ifRuleClassInRuleBlackList(ruleClass)) {
          +            return true;
          +        }
          +
          +        ASTCompilationUnit nodeRoot = getNodeRoot(node);
          +        if (nodeRoot != null) {
          +            String packageName = nodeRoot.getPackageName();
          +            if (NameListConfig.getNameListService().ifPackageNameInPackageBlackList(packageName)) {
          +                return true;
          +            }
          +        }
          +
          +        if (node instanceof ScopedNode) {
          +            ScopedNode scopedNode = (ScopedNode) node;
          +            Scope scope = scopedNode.getScope();
          +            while (scope != null && !(scope instanceof ClassScope)) {
          +                scope = scope.getParent();
          +            }
          +            if (scope != null) {
          +                String className = ((ClassScope) scope).getClassName();
          +                if (NameListConfig.getNameListService().ifClassNameInClassBlackList(className)) {
          +                    return true;
          +                }
          +                return NameListConfig.getNameListService().ifRuleClassNameClassNamePairInPairIgnoreList(ruleClass,
          +                        className);
          +            }
          +        }
          +
          +        return false;
          +    }
          +
          +    @Nullable
          +    private static ASTCompilationUnit getNodeRoot(@Nullable Node node) {
          +        while (node != null) {
          +            if (node instanceof ASTCompilationUnit) {
          +                return (ASTCompilationUnit) node;
          +            }
          +            node = node.getParent();
          +        }
          +        return null;
          +    }
          +
           }
          diff --git a/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/namelist/NameListConfig.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/namelist/NameListConfig.java
          new file mode 100644
          index 000000000..1bc4a3c59
          --- /dev/null
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/namelist/NameListConfig.java
          @@ -0,0 +1,61 @@
          +/*
          + * 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.xenoamess.p3c.pmd.lang.java.util.namelist;
          +
          +import com.xenoamess.p3c.pmd.lang.java.util.SpiLoader;
          +import org.jetbrains.annotations.NotNull;
          +
          +import java.io.File;
          +
          +/**
          + * @author changle.lq
          + * @date 2017/03/27
          + */
          +public class NameListConfig {
          +    private static @NotNull
          +    NameListService nameListService = createNameListService();
          +
          +    public static synchronized @NotNull
          +    NameListService renewNameListService() {
          +        setNameListService(createNameListService());
          +        return getNameListService();
          +    }
          +
          +    public static synchronized @NotNull
          +    NameListService renewNameListService(@NotNull File patchConfigFile) {
          +        setNameListService(createNameListService());
          +        getNameListService().loadPatchConfigFile(patchConfigFile);
          +        return getNameListService();
          +    }
          +
          +    private static @NotNull
          +    NameListService createNameListService() {
          +        NameListService instance = SpiLoader.getInstance(NameListService.class);
          +        if (instance == null) {
          +            instance = new NameListServiceImpl();
          +        }
          +        return instance;
          +    }
          +
          +    public static synchronized @NotNull
          +    NameListService getNameListService() {
          +        return nameListService;
          +    }
          +
          +    public static synchronized void setNameListService(@NotNull NameListService nameListService) {
          +        NameListConfig.nameListService = nameListService;
          +    }
          +}
          diff --git a/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/namelist/NameListService.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/namelist/NameListService.java
          new file mode 100644
          index 000000000..0434ba748
          --- /dev/null
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/namelist/NameListService.java
          @@ -0,0 +1,83 @@
          +/*
          + * 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.xenoamess.p3c.pmd.lang.java.util.namelist;
          +
          +import org.jetbrains.annotations.NotNull;
          +import org.jetbrains.annotations.Nullable;
          +
          +import java.io.File;
          +import java.util.List;
          +import java.util.Map;
          +
          +/**
          + * @author changle.lq
          + * @date 2017/03/23
          + */
          +public interface NameListService {
          +
          +    /**
          +     * get name list
          +     * @param className class name
          +     * @param name type name
          +     * @return name list
          +     */
          +    List getNameList(String className, String name);
          +
          +    /**
          +     * get config
          +     * @param className class name
          +     * @param name type name
          +     * @return name list
          +     */
          +    Map getNameMap(String className, String name);
          +
          +    /**
          +     * patch config from a patch file.
          +     * @param file additional config file
          +     */
          +    void loadPatchConfigFile(
          +            @NotNull File file
          +    );
          +
          +    /**
          +     * check if a rule is in rule black list.
          +     * @param ruleClass rule class
          +     * @return true if in rule black list
          +     */
          +    boolean ifRuleClassInRuleBlackList(Class ruleClass);
          +
          +    /**
          +     * check if class name is in class black list.
          +     * @param className class name
          +     * @return true if in class black list
          +     */
          +    boolean ifClassNameInClassBlackList(String className);
          +
          +    /**
          +     * check if package name is in package black list.
          +     * @param packageName package name
          +     * @return true if in package black list
          +     */
          +    boolean ifPackageNameInPackageBlackList(@Nullable String packageName);
          +
          +    /**
          +     * check if class name is in class name pair black list.
          +     * @param ruleClass rule class
          +     * @param className class name
          +     * @return true if in class black list
          +     */
          +    boolean ifRuleClassNameClassNamePairInPairIgnoreList(Class ruleClass, String className);
          +}
          diff --git a/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/namelist/NameListServiceImpl.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/namelist/NameListServiceImpl.java
          new file mode 100644
          index 000000000..57fd3a213
          --- /dev/null
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/java/util/namelist/NameListServiceImpl.java
          @@ -0,0 +1,163 @@
          +/*
          + * 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.xenoamess.p3c.pmd.lang.java.util.namelist;
          +
          +import com.xenoamess.p3c.pmd.config.P3cConfigDataBean;
          +import com.xenoamess.x8l.ContentNode;
          +import com.xenoamess.x8l.X8lTree;
          +import com.xenoamess.x8l.databind.X8lDataBeanFieldScheme;
          +import com.xenoamess.x8l.dealers.JsonDealer;
          +import com.xenoamess.x8l.dealers.X8lDealer;
          +import org.apache.commons.io.IOUtils;
          +import org.jetbrains.annotations.NotNull;
          +import org.jetbrains.annotations.Nullable;
          +
          +import java.io.File;
          +import java.io.IOException;
          +import java.io.InputStream;
          +import java.util.List;
          +import java.util.Map;
          +import java.util.Set;
          +
          +import static com.xenoamess.x8l.databind.X8lDataBeanDefaultParser.getLastFromList;
          +
          +/**
          + * @author changle.lq
          + * @date 2017/03/27
          + */
          +public class NameListServiceImpl implements NameListService {
          +
          +    public static final String P3C_X8L_CONFIG_FILE_NAME = "p3c_config.x8l";
          +    public static final String P3C_JSON_CONFIG_FILE_NAME = "p3c_config.json";
          +    public static final String DEFAULT_P3C_CONFIG_FILE_NAME = "p3c_config.default.x8l";
          +    private final P3cConfigDataBean p3cConfigDataBean;
          +
          +    public NameListServiceImpl() {
          +        this(true);
          +    }
          +
          +    public NameListServiceImpl(boolean ifLoadCustomerConfigX8lTree) {
          +        p3cConfigDataBean = initP3cConfigDataBean(ifLoadCustomerConfigX8lTree);
          +    }
          +
          +    private static P3cConfigDataBean initP3cConfigDataBean(boolean ifLoadCustomerConfigX8lTreeLocal) {
          +        P3cConfigDataBean p3cConfigDataBeanLocal = new P3cConfigDataBean();
          +        try {
          +            try (InputStream inputStream =
          +                         NameListServiceImpl.class.getClassLoader()
          +                                 .getResourceAsStream(DEFAULT_P3C_CONFIG_FILE_NAME);
          +                 InputStream bufferedInputStream = IOUtils.toBufferedInputStream(inputStream)
          +            ) {
          +                p3cConfigDataBeanLocal.setP3cConfigX8lTree(X8lTree.load(bufferedInputStream));
          +            }
          +        } catch (IOException ex) {
          +            throw new IllegalStateException("Load p3c_config.default.x8l fail", ex);
          +        }
          +
          +        if (ifLoadCustomerConfigX8lTreeLocal) {
          +            File p3cX8lConfigFile = new File(P3C_X8L_CONFIG_FILE_NAME);
          +            if (p3cX8lConfigFile.exists() && p3cX8lConfigFile.isFile()) {
          +                p3cConfigDataBeanLocal.tryPatchP3cConfigDataBean(p3cX8lConfigFile, X8lDealer.INSTANCE);
          +            } else {
          +                p3cConfigDataBeanLocal.tryPatchP3cConfigDataBean(new File(P3C_JSON_CONFIG_FILE_NAME), JsonDealer.INSTANCE);
          +            }
          +        }
          +        p3cConfigDataBeanLocal.loadFromX8lTree(p3cConfigDataBeanLocal.getP3cConfigX8lTree());
          +        return p3cConfigDataBeanLocal;
          +    }
          +
          +    @Override
          +    public void loadPatchConfigFile(@NotNull File file) {
          +        String fileName = file.getName();
          +        if (fileName.endsWith(X8lTree.STRING_X8L)) {
          +            this.getP3cConfigDataBean().tryPatchP3cConfigDataBean(file, X8lDealer.INSTANCE);
          +        }
          +        if (fileName.endsWith(X8lTree.STRING_JSON)) {
          +            this.getP3cConfigDataBean().tryPatchP3cConfigDataBean(file, JsonDealer.INSTANCE);
          +        }
          +    }
          +
          +    @Override
          +    public List getNameList(String className, String name) {
          +        return getContentNode(className, name).asStringListTrimmed();
          +    }
          +
          +    @Override
          +    public Map getNameMap(String className, String name) {
          +        return getContentNode(className, name).asStringMapTrimmed();
          +    }
          +
          +    @Override
          +    public boolean ifRuleClassInRuleBlackList(Class ruleClass) {
          +        return ifStringInRuleBlackList(ruleClass.getSimpleName())
          +                || ifStringInRuleBlackList(ruleClass.getCanonicalName());
          +    }
          +
          +    public boolean ifStringInRuleBlackList(String string) {
          +        return this.getP3cConfigDataBean().getRuleBlackListSet().contains(string);
          +    }
          +
          +    @Override
          +    public boolean ifClassNameInClassBlackList(String className) {
          +        return this.getP3cConfigDataBean().getClassBlackListSet().contains(className);
          +    }
          +
          +    @Override
          +    public boolean ifPackageNameInPackageBlackList(@Nullable String packageName) {
          +        if (packageName == null) {
          +            return false;
          +        }
          +        Set packageBlackListSet = this.getP3cConfigDataBean().getPackageBlackListSet();
          +        if (packageBlackListSet != null) {
          +            for (String packageBlack : packageBlackListSet) {
          +                if (packageName.startsWith(packageBlack)) {
          +                    return true;
          +                }
          +            }
          +        }
          +        return false;
          +    }
          +
          +    @Override
          +    public boolean ifRuleClassNameClassNamePairInPairIgnoreList(Class ruleClass, String className) {
          +        if (getP3cConfigDataBean().getRuleClassPairBlackListMap().containsKey(className)) {
          +            Set ruleSet = getP3cConfigDataBean().getRuleClassPairBlackListMap().get(className);
          +            return ruleSet.contains(ruleClass.getSimpleName()) || ruleSet.contains(ruleClass.getCanonicalName());
          +        }
          +        return false;
          +    }
          +
          +
          +    public ContentNode getContentNode(String className, String name) {
          +        return getLastFromList(
          +                getP3cConfigDataBean().getP3cConfigX8lTree().fetch(
          +                        X8lDataBeanFieldScheme.X8LPATH,
          +                        new String[]{
          +                                "com.alibaba.p3c.pmd.config>rule_config>CONTENT_NODE("
          +                                        + className
          +                                        + ")>CONTENT_NODE("
          +                                        + name
          +                                        + ")"
          +                        },
          +                        ContentNode.class
          +                )
          +        );
          +    }
          +
          +    public P3cConfigDataBean getP3cConfigDataBean() {
          +        return p3cConfigDataBean;
          +    }
          +}
          diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/vm/rule/other/UseQuietReferenceNotationRule.java b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/vm/rule/other/UseQuietReferenceNotationRule.java
          similarity index 85%
          rename from p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/vm/rule/other/UseQuietReferenceNotationRule.java
          rename to p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/vm/rule/other/UseQuietReferenceNotationRule.java
          index 736b7b364..7614a2dde 100644
          --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/vm/rule/other/UseQuietReferenceNotationRule.java
          +++ b/p3c-pmd/src/main/java/com/xenoamess/p3c/pmd/lang/vm/rule/other/UseQuietReferenceNotationRule.java
          @@ -13,14 +13,10 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.vm.rule.other;
          -
          -import java.util.List;
          -import java.util.regex.Pattern;
          -
          -import com.alibaba.p3c.pmd.I18nResources;
          -import com.alibaba.p3c.pmd.lang.AbstractXpathRule;
          +package com.xenoamess.p3c.pmd.lang.vm.rule.other;
           
          +import com.xenoamess.p3c.pmd.I18nResources;
          +import com.xenoamess.p3c.pmd.lang.AbstractAliXpathRule;
           import net.sourceforge.pmd.RuleContext;
           import net.sourceforge.pmd.lang.ast.Node;
           import net.sourceforge.pmd.lang.vm.ast.ASTDirective;
          @@ -28,6 +24,11 @@
           import net.sourceforge.pmd.lang.vm.ast.Token;
           import net.sourceforge.pmd.lang.vm.ast.VmParserConstants;
           
          +import java.util.List;
          +import java.util.regex.Pattern;
          +
          +import static net.sourceforge.pmd.lang.rule.xpath.XPathRuleQuery.XPATH_1_0;
          +
           /**
            * [Mandatory] Variables must add exclamatory mark when passing to velocity engine from backend, like $!{var}.
            * Note: If attribute is null or does not exist, ${var} will be shown directly on web pages.
          @@ -35,23 +36,24 @@
            * @author keriezhang
            * @date 2016/12/14
            */
          -public class UseQuietReferenceNotationRule extends AbstractXpathRule {
          +public class UseQuietReferenceNotationRule extends AbstractAliXpathRule {
               /**
                * scan file path pattern
                */
               private static final Pattern ALLOW_FILE_PATTERN = Pattern.compile(".*(template|velocity).*");
           
          -    private static final String UT_FILE_NAME = "n/a";
          +    private static final String UT_FILE_NAME = "a";
               private static final String MACRO_NAME = "macro";
           
               /**
                * Check reference between two text nodes. Exclude references scan in method.
                */
               private static final String XPATH =
          -        "//Reference[matches(@literal, \"^\\$[^!]+\") and ./preceding-sibling::Text and ./following-sibling::Text]";
          +            "//Reference[matches(@literal, \"^\\$[^!]+\") and ./preceding-sibling::Text and ./following-sibling::Text]";
           
               public UseQuietReferenceNotationRule() {
                   setXPath(XPATH);
          +        this.setVersion(XPATH_1_0);
               }
           
               @Override
          @@ -74,7 +76,7 @@ public void evaluate(Node node, RuleContext ctx) {
           
               @Override
               public void addViolation(Object data, Node node, String arg) {
          -        String name = getIdentifyName((AbstractVmNode)node);
          +        String name = getIdentifyName((AbstractVmNode) node);
                   String text = I18nResources.getMessage("vm.other.UseQuietReferenceNotationRule.violation.msg", name);
                   addViolationWithMessage(data, node, text);
               }
          diff --git a/p3c-pmd/src/main/kotlin/com/alibaba/p3c/pmd/lang/java/rule/concurrent/LockShouldWithTryFinallyRule.kt b/p3c-pmd/src/main/kotlin/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/LockShouldWithTryFinallyRule.kt
          similarity index 67%
          rename from p3c-pmd/src/main/kotlin/com/alibaba/p3c/pmd/lang/java/rule/concurrent/LockShouldWithTryFinallyRule.kt
          rename to p3c-pmd/src/main/kotlin/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/LockShouldWithTryFinallyRule.kt
          index fe2a74ccd..760a30e85 100644
          --- a/p3c-pmd/src/main/kotlin/com/alibaba/p3c/pmd/lang/java/rule/concurrent/LockShouldWithTryFinallyRule.kt
          +++ b/p3c-pmd/src/main/kotlin/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/LockShouldWithTryFinallyRule.kt
          @@ -1,9 +1,9 @@
          -package com.alibaba.p3c.pmd.lang.java.rule.concurrent
          +package com.xenoamess.p3c.pmd.lang.java.rule.concurrent
           
          -import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule
          -import com.alibaba.p3c.pmd.lang.java.rule.util.NodeUtils.LOCK_INTERRUPTIBLY_NAME
          -import com.alibaba.p3c.pmd.lang.java.rule.util.NodeUtils.LOCK_NAME
          -import com.alibaba.p3c.pmd.lang.java.rule.util.NodeUtils.UN_LOCK_NAME
          +import com.xenoamess.p3c.pmd.lang.java.rule.AbstractAliRule
          +import com.xenoamess.p3c.pmd.lang.java.rule.util.NodeUtils.LOCK_INTERRUPTIBLY_NAME
          +import com.xenoamess.p3c.pmd.lang.java.rule.util.NodeUtils.LOCK_NAME
          +import com.xenoamess.p3c.pmd.lang.java.rule.util.NodeUtils.UN_LOCK_NAME
           import net.sourceforge.pmd.lang.java.ast.ASTBlock
           import net.sourceforge.pmd.lang.java.ast.ASTBlockStatement
           import net.sourceforge.pmd.lang.java.ast.ASTFinallyStatement
          @@ -11,6 +11,7 @@ import net.sourceforge.pmd.lang.java.ast.ASTName
           import net.sourceforge.pmd.lang.java.ast.ASTStatementExpression
           import net.sourceforge.pmd.lang.java.ast.ASTTryStatement
           import net.sourceforge.pmd.lang.java.ast.AbstractJavaNode
          +import net.sourceforge.pmd.lang.java.ast.TypeNode
           import java.util.concurrent.locks.Lock
           
           /**
          @@ -34,8 +35,8 @@ open class LockShouldWithTryFinallyRule : AbstractAliRule() {
                       if (lockExpression != null) {
                           // check try finally
                           val tryStatement = findNodeByXpath(
          -                    statement, XPATH_TRY_STATEMENT,
          -                    ASTTryStatement::class.java
          +                        statement, XPATH_TRY_STATEMENT,
          +                        ASTTryStatement::class.java
                           )
                           if (!checkTryStatement(tryStatement)) {
                               addLockViolation(data, lockExpression)
          @@ -45,11 +46,11 @@ open class LockShouldWithTryFinallyRule : AbstractAliRule() {
                       }
                       // find lock expression
                       val expression = findNodeByXpath(
          -                statement, XPATH_LOCK_STATEMENT,
          -                ASTStatementExpression::class.java
          +                    statement, XPATH_LOCK_STATEMENT,
          +                    ASTStatementExpression::class.java
                       ) ?: continue
           
          -            if (!expression.isLock) {
          +            if (!this.haveLock(expression)) {
                           continue
                       }
                       val astName = expression.getFirstDescendantOfType(ASTName::class.java)
          @@ -68,9 +69,9 @@ open class LockShouldWithTryFinallyRule : AbstractAliRule() {
           
               private fun addLockViolation(data: Any, lockExpression: ASTStatementExpression) {
                   addViolationWithMessage(
          -            data, lockExpression,
          -            "java.concurrent.LockShouldWithTryFinallyRule.violation.msg",
          -            arrayOf(getExpressName(lockExpression))
          +                data, lockExpression,
          +                "java.concurrent.LockShouldWithTryFinallyRule.violation.msg",
          +                arrayOf(getExpressName(lockExpression))
                   )
               }
           
          @@ -78,16 +79,18 @@ open class LockShouldWithTryFinallyRule : AbstractAliRule() {
                   if (tryStatement == null) {
                       return false
                   }
          -        val finallyStatement = tryStatement.getFirstChildOfType(ASTFinallyStatement::class.java) ?: return false
          +        val finallyStatement = tryStatement.getFirstChildOfType(ASTFinallyStatement::class.java)
          +                ?: return false
                   val statementExpression = findNodeByXpath(
          -            finallyStatement,
          -            XPATH_UNLOCK_STATEMENT, ASTStatementExpression::class.java
          +                finallyStatement,
          +                XPATH_UNLOCK_STATEMENT, ASTStatementExpression::class.java
                   ) ?: return false
           
          -        if (!statementExpression.isLock) {
          +        if (!haveLock(statementExpression)) {
                       return false
                   }
          -        val astName = statementExpression.getFirstDescendantOfType(ASTName::class.java) ?: return false
          +        val astName = statementExpression.getFirstDescendantOfType(ASTName::class.java)
          +                ?: return false
                   return astName.image?.endsWith(".$UN_LOCK_NAME") ?: false
               }
           
          @@ -113,8 +116,22 @@ open class LockShouldWithTryFinallyRule : AbstractAliRule() {
                   private const val XPATH_TRY_STATEMENT = "Statement/TryStatement"
               }
           
          -    private val ASTStatementExpression?.isLock: Boolean
          -        get() = this?.type?.let {
          -            Lock::class.java.isAssignableFrom(it)
          -        } ?: false
          +    private fun haveLock(node: TypeNode): Boolean {
          +        if (node.type == null) {
          +            return false;
          +        }
          +        if (Lock::class.java.isAssignableFrom(node.type)) {
          +            return true;
          +        }
          +        val numChildren = node.numChildren;
          +        for (i in 0 until numChildren) {
          +            val currentChild = node.getChild(i);
          +            if (currentChild is TypeNode) {
          +                if (this.haveLock(currentChild)) {
          +                    return true;
          +                }
          +            }
          +        }
          +        return false;
          +    }
           }
          diff --git a/p3c-pmd/src/main/resources/META-INF/services/com.alibaba.p3c.pmd.lang.java.util.namelist.NameListService b/p3c-pmd/src/main/resources/META-INF/services/com.xenoamess.p3c.pmd.lang.java.util.namelist.NameListService
          similarity index 100%
          rename from p3c-pmd/src/main/resources/META-INF/services/com.alibaba.p3c.pmd.lang.java.util.namelist.NameListService
          rename to p3c-pmd/src/main/resources/META-INF/services/com.xenoamess.p3c.pmd.lang.java.util.namelist.NameListService
          diff --git a/p3c-pmd/src/main/resources/messages.xml b/p3c-pmd/src/main/resources/messages.xml
          index 848f3edd7..8860085ce 100644
          --- a/p3c-pmd/src/main/resources/messages.xml
          +++ b/p3c-pmd/src/main/resources/messages.xml
          @@ -199,6 +199,13 @@
                   
               
           
          +    
          +        
          +    
          +    
          +        
          +    
          +
               
                   
               
          @@ -269,6 +276,15 @@
               
                   
               
          +    
          +        
          +    
               
               
                   
          @@ -357,6 +373,9 @@
                   
               
           
          +    
          +        
          +    
               
               
                   
          @@ -465,7 +484,7 @@
               
           
               
          -        
          +        
               
               
                   
               
           
          +    
          +        
          +    
           
          diff --git a/p3c-pmd/src/main/resources/messages_en.xml b/p3c-pmd/src/main/resources/messages_en.xml
          index ac0438c44..bc79e027c 100644
          --- a/p3c-pmd/src/main/resources/messages_en.xml
          +++ b/p3c-pmd/src/main/resources/messages_en.xml
          @@ -197,7 +197,14 @@ Explain 3: It is possible that when implementing the lock() method in Lock objec
                   
               
               
          -        
          +        
          +    
          +
          +    
          +        
          +    
          +    
          +        
               
           
               
          @@ -270,6 +277,15 @@ Explain 3: It is possible that when implementing the lock() method in Lock objec
               
                   
               
          +    
          +        
          +    
               
               
                   
          @@ -356,6 +372,9 @@ Explain 3: It is possible that when implementing the lock() method in Lock objec
               
                   
               
          +    
          +        
          +    
           
               
               
          @@ -466,7 +485,7 @@ Note: Do not define Pattern pattern = Pattern.compile(.); within method body.
               
           
               
          -        
          +        
               
               
                   
               
           
          +    
          +        
          +    
           
          diff --git a/p3c-pmd/src/main/resources/namelist.properties b/p3c-pmd/src/main/resources/namelist.properties
          deleted file mode 100644
          index 8941bb5ef..000000000
          --- a/p3c-pmd/src/main/resources/namelist.properties
          +++ /dev/null
          @@ -1,8 +0,0 @@
          -ConstantFieldShouldBeUpperCaseRule_LOG_VARIABLE_TYPE_SET=["Log","Logger"]
          -ConstantFieldShouldBeUpperCaseRule_WHITE_LIST=["serialVersionUID"]
          -LowerCamelCaseVariableNamingRule_WHITE_LIST=["DAOImpl"]
          -PojoMustOverrideToStringRule_POJO_SUFFIX_SET=["DO","DTO","VO","BO"]
          -UndefineMagicConstantRule_LITERAL_WHITE_LIST=["0","1","\\\"\\\"","0.0","1.0","-1","0L","1L"]
          -MethodReturnWrapperTypeRule_PRIMITIVE_TYPE_TO_WAPPER_TYPE={"int":"Integer","boolean":"Boolean","float":"Float","double":"Double","byte":"Byte","short":"Short","long":"Long","char":"Character"}
          -CollectionInitShouldAssignCapacityRule_COLLECTION_TYPE=["HashMap","ConcurrentHashMap"]
          -ClassNamingShouldBeCamelRule_CLASS_NAMING_WHITE_LIST=["Hbase","HBase","ID"]
          diff --git a/p3c-pmd/src/main/resources/p3c_config.default.x8l b/p3c-pmd/src/main/resources/p3c_config.default.x8l
          new file mode 100644
          index 000000000..49a2bbd7b
          --- /dev/null
          +++ b/p3c-pmd/src/main/resources/p3c_config.default.x8l
          @@ -0,0 +1,29 @@
          +
          +    
          +        
          +            Log&Logger>
          +            serialVersionUID>
          +        >
          +        DAOImpl>>
          +        DO&DTO&VO&BO>>
          +        0&1&""&0.0&1.0&-1&0L&1L>>
          +        
          +            
          +                Integer>
          +                Boolean>
          +                Float>
          +                Double>
          +                Byte>
          +                Short>
          +                Long>
          +                Character>
          +                Void>
          +            >
          +        >
          +        HashMap&ConcurrentHashMap>>
          +        Hbase&HBase&ID&ConcurrentHashMap>>
          +    >
          +    >
          +    >
          +    >
          +>
          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 dd295d66a..1d94537e2 100644
          --- a/p3c-pmd/src/main/resources/rulesets/java/ali-comment.xml
          +++ b/p3c-pmd/src/main/resources/rulesets/java/ali-comment.xml
          @@ -5,8 +5,10 @@
               xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
               AlibabaJavaComments
           
          -    
          +    
                   java.comment.CommentsMustBeJavadocFormatRule.rule.desc
                   3
           
          @@ -44,8 +46,9 @@
               
           
               
          +          language="java"
          +          message="java.comment.AbstractMethodOrInterfaceMethodMustUseJavadocRule.rule.msg"
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.comment.AbstractMethodOrInterfaceMethodMustUseJavadocRule">
                   java.comment.AbstractMethodOrInterfaceMethodMustUseJavadocRule.rule.desc
                   3
           
          @@ -64,8 +67,10 @@
                   
               
           
          -    
          +    
                   java.comment.ClassMustHaveAuthorRule.rule.desc
                   3
           
          @@ -83,8 +88,10 @@
                   
               
           
          -    
          +    
                   2
           
                   
          @@ -114,8 +121,9 @@
               
           
               
          +          language="java"
          +          message="java.comment.AvoidCommentBehindStatementRule.rule.msg"
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.comment.AvoidCommentBehindStatementRule">
                   3
           
                   
          @@ -134,8 +142,9 @@
               
           
               
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.comment.RemoveCommentedCodeRule">
                   java.comment.RemoveCommentedCodeRule.rule.desc
                   3
                   
          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 7a76f2a9b..67006bbe3 100644
          --- a/p3c-pmd/src/main/resources/rulesets/java/ali-concurrent.xml
          +++ b/p3c-pmd/src/main/resources/rulesets/java/ali-concurrent.xml
          @@ -9,7 +9,7 @@
                     language="java"
                     since="1.6"
                     message="java.concurrent.ThreadPoolCreationRule.rule.msg"
          -          class="com.alibaba.p3c.pmd.lang.java.rule.concurrent.ThreadPoolCreationRule">
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.concurrent.ThreadPoolCreationRule">
                   java.concurrent.ThreadPoolCreationRule.rule.desc
                   1
                   
          @@ -58,7 +58,7 @@ Positive example 3:
                     language="java"
                     since="1.6"
                     message="java.concurrent.AvoidUseTimerRule.rule.msg"
          -          class="com.alibaba.p3c.pmd.lang.java.rule.concurrent.AvoidUseTimerRule">
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.concurrent.AvoidUseTimerRule">
                   1
                   
                       
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.concurrent.AvoidManuallyCreateThreadRule">
                   java.concurrent.AvoidManuallyCreateThreadRule.rule.desc
                   2
                   
          @@ -100,7 +100,7 @@ Positive example 3:
                     since="1.6"
                     message="java.concurrent.ThreadShouldSetNameRule.rule.msg"
                     dfa="true"
          -          class="com.alibaba.p3c.pmd.lang.java.rule.concurrent.ThreadShouldSetNameRule">
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.concurrent.ThreadShouldSetNameRule">
                   2
                   
                       
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.concurrent.AvoidCallStaticSimpleDateFormatRule">
                   java.concurrent.AvoidCallStaticSimpleDateFormatRule.rule.desc
                   2
                   
          @@ -170,7 +170,7 @@ Positive example 3:
                     since="1.6"
                     message="java.concurrent.ThreadLocalShouldRemoveRule.rule.msg"
                     dfa="true"
          -          class="com.alibaba.p3c.pmd.lang.java.rule.concurrent.ThreadLocalShouldRemoveRule">
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.concurrent.ThreadLocalShouldRemoveRule">
                   2
                   
                       
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.concurrent.AvoidConcurrentCompetitionRandomRule">
                   3
                   
                       
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.concurrent.CountDownShouldInFinallyRule">
                   java.concurrent.CountDownShouldInFinallyRule.rule.desc
                   3
                   
          @@ -290,7 +290,7 @@ Positive example 2:
                     since="1.6"
                     message="java.concurrent.LockShouldWithTryFinallyRule.rule.msg"
                     dfa="true"
          -          class="com.alibaba.p3c.pmd.lang.java.rule.concurrent.LockShouldWithTryFinallyRule">
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.concurrent.LockShouldWithTryFinallyRule">
                   java.concurrent.LockShouldWithTryFinallyRule.rule.desc
                   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 5c1203cd5..b58d08b9e 100644
          --- a/p3c-pmd/src/main/resources/rulesets/java/ali-constant.xml
          +++ b/p3c-pmd/src/main/resources/rulesets/java/ali-constant.xml
          @@ -6,8 +6,9 @@
               AlibabaJavaConstants
           
               
          +          language="java"
          +          message="java.constant.UpperEllRule.rule.msg"
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.constant.UpperEllRule">
                   1
                   
                 
           
               
          +          language="java"
          +          message="java.constant.UndefineMagicConstantRule.rule.msg"
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.constant.UndefineMagicConstantRule">
                   3
           
                   
          diff --git a/p3c-pmd/src/main/resources/rulesets/java/ali-exception.xml b/p3c-pmd/src/main/resources/rulesets/java/ali-exception.xml
          index f872c6518..e46b98162 100644
          --- a/p3c-pmd/src/main/resources/rulesets/java/ali-exception.xml
          +++ b/p3c-pmd/src/main/resources/rulesets/java/ali-exception.xml
          @@ -9,7 +9,7 @@
                     language="java"
                     since="1.6"
                     message="java.exception.MethodReturnWrapperTypeRule.rule.msg"
          -          class="com.alibaba.p3c.pmd.lang.java.rule.exception.MethodReturnWrapperTypeRule">
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.exception.MethodReturnWrapperTypeRule">
                   3
                   
                       
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.exception.AvoidReturnInFinallyRule">
                   2
                   
                       
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.exception.TransactionMustHaveRollbackRule">
                   3
                   
                       
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.flowcontrol.SwitchStatementRule">
                   2
           
                   
          @@ -24,10 +24,27 @@
                   
               
           
          +    
          +        2
          +
          +        
          +             4;
          +        case 2 -> 5;
          +        default -> 6;
          +    }
          +			]]>
          +        
          +    
          +
               
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.flowcontrol.NeedBraceRule">
                   1
           
                   
          @@ -42,7 +59,7 @@
               
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.flowcontrol.AvoidComplexConditionRule">
                   java.flowcontrol.AvoidComplexConditionRule.rule.desc
                   3
           
          @@ -68,7 +85,7 @@ Positive example:
               
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.flowcontrol.AvoidNegationOperatorRule">
                   java.flowcontrol.AvoidNegationOperatorRule.rule.desc
                   3
           
          diff --git a/p3c-pmd/src/main/resources/rulesets/java/ali-naming.xml b/p3c-pmd/src/main/resources/rulesets/java/ali-naming.xml
          index 4b0bddb71..9d86895d0 100644
          --- a/p3c-pmd/src/main/resources/rulesets/java/ali-naming.xml
          +++ b/p3c-pmd/src/main/resources/rulesets/java/ali-naming.xml
          @@ -10,7 +10,7 @@
                     language="java"
                     since="1.6"
                     message="java.naming.ClassNamingShouldBeCamelRule.rule.msg"
          -          class="com.alibaba.p3c.pmd.lang.java.rule.naming.ClassNamingShouldBeCamelRule">
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.naming.ClassNamingShouldBeCamelRule">
                   3
               
           
          @@ -18,7 +18,7 @@
                     language="java"
                     since="1.4"
                     message="java.naming.AbstractClassShouldStartWithAbstractNamingRule.rule.msg"
          -          class="com.alibaba.p3c.pmd.lang.java.rule.naming.AbstractClassShouldStartWithAbstractNamingRule">
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.naming.AbstractClassShouldStartWithAbstractNamingRule">
                   2
                   
                       
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.naming.ExceptionClassShouldEndWithExceptionRule">
                   2
                   
                       
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.naming.TestClassShouldEndWithTestNamingRule">
                   3
                   
                       
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.naming.LowerCamelCaseVariableNamingRule">
                   2
               
           
          @@ -72,7 +72,7 @@
                     language="java"
                     since="1.6"
                     message="java.naming.AvoidStartWithDollarAndUnderLineNamingRule.rule.msg"
          -          class="com.alibaba.p3c.pmd.lang.java.rule.naming.AvoidStartWithDollarAndUnderLineNamingRule">
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.naming.AvoidStartWithDollarAndUnderLineNamingRule">
                   2
               
           
          @@ -80,7 +80,7 @@
                     language="java"
                     since="1.6"
                     message="java.naming.ConstantFieldShouldBeUpperCaseRule.rule.msg"
          -          class="com.alibaba.p3c.pmd.lang.java.rule.naming.ConstantFieldShouldBeUpperCaseRule">
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.naming.ConstantFieldShouldBeUpperCaseRule">
                   2
                   
                       
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.naming.ServiceOrDaoClassShouldEndWithImplRule">
                   2
                   
                       
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.naming.PackageNamingRule">
                   3
                   
                       
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.naming.BooleanPropertyShouldNotStartWithIsRule">
                   2
                   
                       
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.naming.ArrayNamingShouldHaveBracketRule">
                   3
                   
                       
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.oop.EqualsAvoidNullRule">
                   2
           
                   
          @@ -26,7 +26,7 @@
               
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.oop.WrapperTypeEqualityRule">
                   java.oop.WrapperTypeEqualityRule.rule.desc
                   1
           
          @@ -44,7 +44,7 @@
               
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.oop.PojoMustUsePrimitiveFieldRule">
                   java.oop.PojoMustUsePrimitiveFieldRule.rule.msg.desc
                   3
           
          @@ -61,7 +61,7 @@
               
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.oop.PojoNoDefaultValueRule">
                   3
           
                   
          @@ -77,7 +77,7 @@
               
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.oop.PojoMustOverrideToStringRule">
                   java.oop.PojoMustOverrideToStringRule.rule.desc
                   3
           
          @@ -107,7 +107,7 @@
               
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.oop.StringConcatRule">
                   java.oop.StringConcatRule.rule.msg.desc
                   3
           
          @@ -135,7 +135,7 @@ Positive example:
               
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.oop.BigDecimalAvoidDoubleConstructorRule">
                   java.oop.BigDecimalAvoidDoubleConstructorRule.rule.msg.desc
                   3
           
          @@ -153,5 +153,4 @@ Positive example:
           ]]>
                   
               
          -
           
          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 b2d07e8a9..cbd6e90d5 100644
          --- a/p3c-pmd/src/main/resources/rulesets/java/ali-orm.xml
          +++ b/p3c-pmd/src/main/resources/rulesets/java/ali-orm.xml
          @@ -9,7 +9,7 @@
                     language="java"
                     since="1.6"
                     message="java.naming.IbatisMethodQueryForListRule.rule.msg"
          -          class="com.alibaba.p3c.pmd.lang.java.rule.orm.IbatisMethodQueryForListRule">
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.orm.IbatisMethodQueryForListRule">
                   3
               
           
          diff --git a/p3c-pmd/src/main/resources/rulesets/java/ali-other.xml b/p3c-pmd/src/main/resources/rulesets/java/ali-other.xml
          index c9b26ed3c..892d541d5 100644
          --- a/p3c-pmd/src/main/resources/rulesets/java/ali-other.xml
          +++ b/p3c-pmd/src/main/resources/rulesets/java/ali-other.xml
          @@ -7,7 +7,7 @@
           
               
          +        class="com.xenoamess.p3c.pmd.lang.java.rule.other.AvoidPatternCompileInMethodRule">
                   java.other.AvoidPatternCompileInMethodRule.rule.desc
                   1
                   
          @@ -27,7 +27,7 @@
           
               
          +        class="com.xenoamess.p3c.pmd.lang.java.rule.other.AvoidApacheBeanUtilsCopyRule">
                   java.other.AvoidApacheBeanUtilsCopyRule.rule.desc
                   1
                   
          @@ -42,7 +42,7 @@
           
               
          +        class="com.xenoamess.p3c.pmd.lang.java.rule.other.AvoidNewDateGetTimeRule">
                   java.other.AvoidNewDateGetTimeRule.rule.desc
                   1
                   
          @@ -64,7 +64,7 @@
           
               
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.other.AvoidMissUseOfMathRandomRule">
                   3
                   
           
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.other.MethodTooLongRule">
                   java.other.MethodTooLongRule.rule.desc
                   3
               
           
               
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.other.UseRightCaseForDateFormatRule">
                   java.other.UseRightCaseForDateFormatRule.rule.desc
                   2
                   
          @@ -108,7 +108,7 @@ Positive example:
           
               
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.other.AvoidDoubleOrFloatEqualCompareRule">
                   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 1df62235e..2590e3cdd 100644
          --- a/p3c-pmd/src/main/resources/rulesets/java/ali-set.xml
          +++ b/p3c-pmd/src/main/resources/rulesets/java/ali-set.xml
          @@ -1,133 +1,138 @@
           
           
           
          +         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">
               AlibabaJavaSets
           
               
          +          language="java"
          +          message="java.set.ClassCastExceptionWithToArrayRule.rule.msg"
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.set.ClassCastExceptionWithToArrayRule">
                   2
                   
          -        
                   
                   
          -        
                   
               
           
               
          +          language="java"
          +          message="java.set.UnsupportedExceptionWithModifyAsListRule.rule.msg"
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.set.UnsupportedExceptionWithModifyAsListRule">
                   2
                   
          -        t   = Arrays.asList("a","b","c"); 
          +   List t   = Arrays.asList("a","b","c");
              //warn
              t.add("22");
              //warn
              t.remove("22");
              //warn
          -   t.clear(); 
          +   t.clear();
                    ]]>
          -         
          +        
               
           
               
          +          language="java"
          +          message="java.set.ClassCastExceptionWithSubListToArrayListRule.rule.msg"
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.set.ClassCastExceptionWithSubListToArrayListRule">
                   java.set.ClassCastExceptionWithSubListToArrayListRule.rule.msg.desc
                   2
                   
          -         list = new ArrayList();
              list.add("22");
              //warn
          -   List test = (ArrayList) list.subList(0, 1);	 
          +   List test = (ArrayList) list.subList(0, 1);
                    ]]>
                   
                   
          -         list2 = new ArrayList(list.subList(0, 1));
                    ]]>
          -         
          +        
               
           
               
          +          language="java"
          +          message="java.set.ConcurrentExceptionWithModifyOriginSubListRule.rule.msg"
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.set.ConcurrentExceptionWithModifyOriginSubListRule">
                   2
                   
          -       originList = new ArrayList();
              originList.add("22");
              List subList = originList.subList(0, 1);
              //warn
          -   originList.add("22"); 
          +   originList.add("22");
                  ]]>
          -         
          +        
               
           
           
               
          +          language="java"
          +          message="java.set.DontModifyInForeachCircleRule.rule.msg"
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.set.DontModifyInForeachCircleRule">
                   1
           
                   
          -         originList = new ArrayList();
              originList.add("22");
          -   for (String item : originList) { 
          +   for (String item : originList) {
                 //warn
                 list.add("bb");
          -   }  
          +   }
                   ]]>
          -       
          -      
          -        it=b.iterator();		 
          -   while(it.hasNext()){                      
          -      Integer temp =  it.next();             
          +        
          +        
          +             it=b.iterator();
          +   while(it.hasNext()){
          +      Integer temp =  it.next();
                 if (delCondition) {
                     it.remove();
                 }
              }
                    ]]>
          -      
          +        
               
           
               
          +          language="java"
          +          message="java.set.CollectionInitShouldAssignCapacityRule.rule.msg"
          +          class="com.xenoamess.p3c.pmd.lang.java.rule.set.CollectionInitShouldAssignCapacityRule">
                   java.set.CollectionInitShouldAssignCapacityRule.rule.msg.desc
                   3
                   
          -         map = new HashMap();
          -    
          +
                   ]]>
          -       
          -      
          -       
          +        
          +             map = new HashMap(16);
                    ]]>
          -      
          +        
               
          -
           
          diff --git a/p3c-pmd/src/main/resources/rulesets/java/xenoamess-additional.xml b/p3c-pmd/src/main/resources/rulesets/java/xenoamess-additional.xml
          new file mode 100644
          index 000000000..d818eabde
          --- /dev/null
          +++ b/p3c-pmd/src/main/resources/rulesets/java/xenoamess-additional.xml
          @@ -0,0 +1,95 @@
          +
          +
          +
          +    XenoAmessAdditional
          +    
          +        4
          +        
          +            
          +        
          +    
          +    
          +        2
          +        
          +             {
          +
          +            @SneakyThrows(value = {IOException.class})
          +            @Override
          +            public Object apply(File file) {
          +                return FileUtils.readFileToString(file, StandardCharsets.UTF_8);
          +            }
          +
          +        }
          +
          +    Negative example:
          +        import lombok.SneakyThrows;
          +        import org.apache.commons.io.FileUtils;
          +
          +        import java.io.File;
          +        import java.io.IOException;
          +        import java.nio.charset.StandardCharsets;
          +        import java.util.function.Function;
          +
          +        public class FileReadFunction implements Function {
          +
          +            @SneakyThrows
          +            @Override
          +            public Object apply(File file) {
          +                return FileUtils.readFileToString(file, StandardCharsets.UTF_8);
          +            }
          +
          +        }
          +             ]]>
          +        
          +    
          +
          diff --git a/p3c-pmd/src/main/resources/rulesets/java/xenoamess-deprecated.xml b/p3c-pmd/src/main/resources/rulesets/java/xenoamess-deprecated.xml
          new file mode 100644
          index 000000000..08ee33a2c
          --- /dev/null
          +++ b/p3c-pmd/src/main/resources/rulesets/java/xenoamess-deprecated.xml
          @@ -0,0 +1,25 @@
          +
          +
          +
          +    XenoAmessDeprecated
          +    
          +        5
          +        
          +            
          +        
          +    
          +
          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 80e149152..f28808aab 100644
          --- a/p3c-pmd/src/main/resources/rulesets/vm/ali-other.xml
          +++ b/p3c-pmd/src/main/resources/rulesets/vm/ali-other.xml
          @@ -6,7 +6,7 @@
               AlibabaVelocityOthers
               
          +        class="com.xenoamess.p3c.pmd.lang.vm.rule.other.UseQuietReferenceNotationRule">
                   vm.other.UseQuietReferenceNotationRule.rule.desc
                   3
                   
          diff --git a/p3c-pmd/src/site/resources/checkstyle/checkstyle-suppressions.xml b/p3c-pmd/src/site/resources/checkstyle/checkstyle-suppressions.xml
          new file mode 100644
          index 000000000..c087bb5c2
          --- /dev/null
          +++ b/p3c-pmd/src/site/resources/checkstyle/checkstyle-suppressions.xml
          @@ -0,0 +1,32 @@
          +
          +
          +
          +
          +    
          +    
          +    
          +    
          +    
          +    
          +    
          +
          diff --git a/p3c-pmd/src/site/resources/checkstyle/checkstyle.xml b/p3c-pmd/src/site/resources/checkstyle/checkstyle.xml
          new file mode 100644
          index 000000000..9d31cf33e
          --- /dev/null
          +++ b/p3c-pmd/src/site/resources/checkstyle/checkstyle.xml
          @@ -0,0 +1,60 @@
          +
          +
          +
          +
          +
          +
          +
          +  
          +  
          +    
          +  
          +  
          +    
          +  
          +  
          +    
          +    
          +    
          +  
          +  
          +    
          +  
          +  
          +    
          +    
          +    
          +    
          +    
          +    
          +      
          +    
          +    
          +    
          +    
          +    
          +    
          +    
          +    
          +    
          +    
          +  
          +
          diff --git a/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/IfVoidIsPrimitiveTest.java b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/IfVoidIsPrimitiveTest.java
          new file mode 100644
          index 000000000..449d22c7a
          --- /dev/null
          +++ b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/IfVoidIsPrimitiveTest.java
          @@ -0,0 +1,12 @@
          +package com.xenoamess.p3c.pmd;
          +
          +import org.junit.Test;
          +
          +import static org.junit.Assert.assertTrue;
          +
          +public class IfVoidIsPrimitiveTest {
          +    @Test
          +    public void test() {
          +        assertTrue(Void.TYPE.isPrimitive());
          +    }
          +}
          diff --git a/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/config/TestConfig.java b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/config/TestConfig.java
          new file mode 100644
          index 000000000..7344ee7d7
          --- /dev/null
          +++ b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/config/TestConfig.java
          @@ -0,0 +1,93 @@
          +package com.xenoamess.p3c.pmd.config;
          +
          +import com.xenoamess.p3c.pmd.lang.java.util.namelist.NameListServiceImpl;
          +import org.junit.Test;
          +
          +import java.util.ArrayList;
          +import java.util.Arrays;
          +import java.util.Collections;
          +import java.util.HashMap;
          +
          +import static org.junit.Assert.assertEquals;
          +
          +public class TestConfig {
          +    @Test
          +    public void testLoadDefaultConfig() {
          +        NameListServiceImpl nameListService = new NameListServiceImpl(false);
          +
          +        assertEquals(
          +                nameListService.getNameList(
          +                        "ConstantFieldShouldBeUpperCaseRule",
          +                        "LOG_VARIABLE_TYPE_SET"
          +                ),
          +                new ArrayList<>(Arrays.asList("Log", "Logger"))
          +        );
          +
          +        assertEquals(
          +                nameListService.getNameList(
          +                        "ConstantFieldShouldBeUpperCaseRule",
          +                        "WHITE_LIST"
          +                ),
          +                new ArrayList<>(Collections.singletonList("serialVersionUID"))
          +        );
          +
          +        assertEquals(
          +                nameListService.getNameList(
          +                        "LowerCamelCaseVariableNamingRule",
          +                        "WHITE_LIST"
          +                ),
          +                new ArrayList<>(Collections.singletonList("DAOImpl"))
          +        );
          +
          +        assertEquals(
          +                nameListService.getNameList(
          +                        "PojoMustOverrideToStringRule",
          +                        "POJO_SUFFIX_SET"
          +                ),
          +                new ArrayList<>(Arrays.asList("DO", "DTO", "VO", "BO"))
          +        );
          +
          +        assertEquals(
          +                nameListService.getNameList(
          +                        "UndefineMagicConstantRule",
          +                        "LITERAL_WHITE_LIST"
          +                ),
          +                new ArrayList<>(Arrays.asList("0", "1", "\"\"", "0.0", "1.0", "-1", "0L", "1L"))
          +        );
          +
          +        HashMap mapa = new HashMap<>();
          +        mapa.put("int", "Integer");
          +        mapa.put("boolean", "Boolean");
          +        mapa.put("float", "Float");
          +        mapa.put("double", "Double");
          +        mapa.put("byte", "Byte");
          +        mapa.put("short", "Short");
          +        mapa.put("long", "Long");
          +        mapa.put("char", "Character");
          +        mapa.put("void", "Void");
          +        assertEquals(
          +                nameListService.getNameMap(
          +                        "MethodReturnWrapperTypeRule",
          +                        "PRIMITIVE_TYPE_TO_WRAPPER_TYPE"
          +                ),
          +                mapa
          +        );
          +
          +        assertEquals(
          +                nameListService.getNameList(
          +                        "CollectionInitShouldAssignCapacityRule",
          +                        "COLLECTION_TYPE"
          +                ),
          +                new ArrayList<>(Arrays.asList("HashMap", "ConcurrentHashMap"))
          +        );
          +
          +        assertEquals(
          +                nameListService.getNameList(
          +                        "ClassNamingShouldBeCamelRule",
          +                        "CLASS_NAMING_WHITE_LIST"
          +                ),
          +                new ArrayList<>(Arrays.asList("Hbase", "HBase", "ID", "ConcurrentHashMap"))
          +        );
          +
          +    }
          +}
          diff --git a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/comment/CommentRulesTest.java b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/comment/CommentRulesTest.java
          similarity index 95%
          rename from p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/comment/CommentRulesTest.java
          rename to p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/comment/CommentRulesTest.java
          index f2d4b594e..51e3dc99f 100644
          --- a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/comment/CommentRulesTest.java
          +++ b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/comment/CommentRulesTest.java
          @@ -13,13 +13,13 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.comment;
          +package com.xenoamess.p3c.pmd.lang.java.rule.comment;
           
           import net.sourceforge.pmd.testframework.SimpleAggregatorTst;
           
           /**
            * Test for comment rules.
          - * 
          + *
            * @author keriezhang
            * @date 2017/06/18
            *
          diff --git a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/ConcurrentRuleTest.java b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/ConcurrentRuleTest.java
          similarity index 96%
          rename from p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/ConcurrentRuleTest.java
          rename to p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/ConcurrentRuleTest.java
          index 7b2b8799d..0908d1153 100644
          --- a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/ConcurrentRuleTest.java
          +++ b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/ConcurrentRuleTest.java
          @@ -13,7 +13,7 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.concurrent;
          +package com.xenoamess.p3c.pmd.lang.java.rule.concurrent;
           
           import net.sourceforge.pmd.testframework.SimpleAggregatorTst;
           
          diff --git a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/constant/ConstantRulesTest.java b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/constant/ConstantRulesTest.java
          similarity index 94%
          rename from p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/constant/ConstantRulesTest.java
          rename to p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/constant/ConstantRulesTest.java
          index f4d8631a8..6e309b3bc 100644
          --- a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/constant/ConstantRulesTest.java
          +++ b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/constant/ConstantRulesTest.java
          @@ -13,7 +13,7 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.constant;
          +package com.xenoamess.p3c.pmd.lang.java.rule.constant;
           
           import net.sourceforge.pmd.testframework.SimpleAggregatorTst;
           
          @@ -27,7 +27,7 @@
           public class ConstantRulesTest extends SimpleAggregatorTst {
           
               private static final String RULESET = "java-ali-constant";
          -    
          +
               @Override
               public void setUp() {
                   addRule(RULESET, "UpperEllRule");
          diff --git a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/exception/ExceptionRulesTest.java b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/exception/ExceptionRulesTest.java
          similarity index 95%
          rename from p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/exception/ExceptionRulesTest.java
          rename to p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/exception/ExceptionRulesTest.java
          index 98f842534..4eb429b7a 100644
          --- a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/exception/ExceptionRulesTest.java
          +++ b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/exception/ExceptionRulesTest.java
          @@ -13,7 +13,7 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.exception;
          +package com.xenoamess.p3c.pmd.lang.java.rule.exception;
           
           import net.sourceforge.pmd.testframework.SimpleAggregatorTst;
           
          diff --git a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/FlowControlRuleTest.java b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/flowcontrol/FlowControlRuleTest.java
          similarity index 91%
          rename from p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/FlowControlRuleTest.java
          rename to p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/flowcontrol/FlowControlRuleTest.java
          index c679434f4..0c697c9ba 100644
          --- a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/FlowControlRuleTest.java
          +++ b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/flowcontrol/FlowControlRuleTest.java
          @@ -13,7 +13,7 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.flowcontrol;
          +package com.xenoamess.p3c.pmd.lang.java.rule.flowcontrol;
           
           import net.sourceforge.pmd.testframework.SimpleAggregatorTst;
           
          @@ -31,6 +31,7 @@ public class FlowControlRuleTest extends SimpleAggregatorTst {
               @Override
               public void setUp() {
                   addRule(RULESET, "SwitchStatementRule");
          +        addRule(RULESET, "SwitchExpressionRule");
                   addRule(RULESET, "NeedBraceRule");
                   addRule(RULESET, "AvoidComplexConditionRule");
                   addRule(RULESET, "AvoidNegationOperatorRule");
          diff --git a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/naming/NamingRulesTest.java b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/NamingRulesTest.java
          similarity index 96%
          rename from p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/naming/NamingRulesTest.java
          rename to p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/NamingRulesTest.java
          index 501523c65..c173a1c4e 100644
          --- a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/naming/NamingRulesTest.java
          +++ b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/naming/NamingRulesTest.java
          @@ -13,7 +13,7 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.naming;
          +package com.xenoamess.p3c.pmd.lang.java.rule.naming;
           
           import net.sourceforge.pmd.testframework.SimpleAggregatorTst;
           
          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/xenoamess/p3c/pmd/lang/java/rule/oop/OopRuleTest.java
          similarity index 96%
          rename from p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/oop/OopRuleTest.java
          rename to p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/oop/OopRuleTest.java
          index 9ab81aa27..82c4e392c 100644
          --- a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/oop/OopRuleTest.java
          +++ b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/oop/OopRuleTest.java
          @@ -13,7 +13,7 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.oop;
          +package com.xenoamess.p3c.pmd.lang.java.rule.oop;
           
           import net.sourceforge.pmd.testframework.SimpleAggregatorTst;
           
          diff --git a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/orm/OrmRulesTest.java b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/orm/OrmRulesTest.java
          similarity index 94%
          rename from p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/orm/OrmRulesTest.java
          rename to p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/orm/OrmRulesTest.java
          index 010026fd8..a4a690faa 100644
          --- a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/orm/OrmRulesTest.java
          +++ b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/orm/OrmRulesTest.java
          @@ -13,7 +13,7 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.orm;
          +package com.xenoamess.p3c.pmd.lang.java.rule.orm;
           
           import net.sourceforge.pmd.testframework.SimpleAggregatorTst;
           
          @@ -31,4 +31,4 @@ public class OrmRulesTest extends SimpleAggregatorTst {
               public void setUp() {
                   addRule(RULESET, "IbatisMethodQueryForListRule");
               }
          -}
          \ No newline at end of file
          +}
          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/xenoamess/p3c/pmd/lang/java/rule/other/OtherRulesTest.java
          similarity index 85%
          rename from p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/other/OtherRulesTest.java
          rename to p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/other/OtherRulesTest.java
          index 7986c6655..070d40c48 100644
          --- a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/other/OtherRulesTest.java
          +++ b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/other/OtherRulesTest.java
          @@ -13,10 +13,9 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.other;
          +package com.xenoamess.p3c.pmd.lang.java.rule.other;
           
           import net.sourceforge.pmd.testframework.SimpleAggregatorTst;
          -import org.junit.Test;
           
           /**
            * Test for other java rules.
          @@ -36,11 +35,9 @@ public void setUp() {
                   addRule(RULESET, "AvoidPatternCompileInMethodRule");
                   addRule(RULESET, "AvoidMissUseOfMathRandomRule");
                   addRule(RULESET, "MethodTooLongRule");
          -        addRule(RULESET,"UseRightCaseForDateFormatRule");
          -        addRule(RULESET,"AvoidDoubleOrFloatEqualCompareRule");
          +        addRule(RULESET, "UseRightCaseForDateFormatRule");
          +        addRule(RULESET, "AvoidDoubleOrFloatEqualCompareRule");
               }
           
           
          -
          -
           }
          diff --git a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/other/UseRightCaseForDateFormatRuleTest.java b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/other/UseRightCaseForDateFormatRuleTest.java
          similarity index 83%
          rename from p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/other/UseRightCaseForDateFormatRuleTest.java
          rename to p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/other/UseRightCaseForDateFormatRuleTest.java
          index fc9ae196e..31a645123 100644
          --- a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/other/UseRightCaseForDateFormatRuleTest.java
          +++ b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/other/UseRightCaseForDateFormatRuleTest.java
          @@ -1,6 +1,6 @@
          -package com.alibaba.p3c.pmd.lang.java.rule.other;
          +package com.xenoamess.p3c.pmd.lang.java.rule.other;
           
          -import com.alibaba.p3c.pmd.testframework.ExtendRuleTst;
          +import com.xenoamess.p3c.pmd.testframework.ExtendRuleTst;
           
           import net.sourceforge.pmd.Rule;
           import org.junit.Test;
          diff --git a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/set/SetRulesTest.java b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/set/SetRulesTest.java
          similarity index 96%
          rename from p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/set/SetRulesTest.java
          rename to p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/set/SetRulesTest.java
          index b96c6e3e9..acac9684b 100644
          --- a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/set/SetRulesTest.java
          +++ b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/set/SetRulesTest.java
          @@ -13,7 +13,7 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.java.rule.set;
          +package com.xenoamess.p3c.pmd.lang.java.rule.set;
           
           import net.sourceforge.pmd.testframework.SimpleAggregatorTst;
           
          diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/message/P3cBundle.kt b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/xenoamess/additional/XenoAmessAdditionalTest.java
          similarity index 55%
          rename from eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/message/P3cBundle.kt
          rename to p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/xenoamess/additional/XenoAmessAdditionalTest.java
          index 1e302f053..74f3d894c 100644
          --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/message/P3cBundle.kt
          +++ b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/xenoamess/additional/XenoAmessAdditionalTest.java
          @@ -13,25 +13,23 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.smartfox.eclipse.message
          +package com.xenoamess.p3c.pmd.lang.java.rule.xenoamess.additional;
           
          -
          -import com.alibaba.p3c.pmd.I18nResources
          -import com.alibaba.smartfox.eclipse.SmartfoxActivator
          -import java.util.Locale
          -import java.util.ResourceBundle
          +import net.sourceforge.pmd.testframework.SimpleAggregatorTst;
           
           /**
          + * Test for set rules.
            *
          - *
          - * @author caikang
          - * @date 2017/06/20
          + * @author shengfang.gsf
          + * @date 2016/12/13
            */
          -object P3cBundle {
          -    private val resourceBundle = ResourceBundle.getBundle("messages.P3cBundle",
          -            Locale(SmartfoxActivator.instance.locale), I18nResources.XmlControl())
          +public class XenoAmessAdditionalTest extends SimpleAggregatorTst {
          +
          +    private static final String RULESET = "java-xenoamess-additional";
           
          -    fun getMessage(key: String): String {
          -        return resourceBundle.getString(key)
          +    @Override
          +    public void setUp() {
          +        addRule(RULESET, "EqualsHashCodeRule");
          +        addRule(RULESET, "SneakyThrowsWithoutExceptionTypeRule");
               }
          -}
          \ No newline at end of file
          +}
          diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/component/AliBaseApplicationComponent.kt b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/xenoamess/deprecated/XenoAmessDeprecatedTest.java
          similarity index 56%
          rename from idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/component/AliBaseApplicationComponent.kt
          rename to p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/xenoamess/deprecated/XenoAmessDeprecatedTest.java
          index 6531f68c0..8c2285f06 100644
          --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/component/AliBaseApplicationComponent.kt
          +++ b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/java/rule/xenoamess/deprecated/XenoAmessDeprecatedTest.java
          @@ -13,25 +13,22 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.smartfox.idea.common.component
          +package com.xenoamess.p3c.pmd.lang.java.rule.xenoamess.deprecated;
           
          -import com.alibaba.smartfox.idea.common.util.PluginVersions
          -import com.intellij.openapi.components.ApplicationComponent
          +import net.sourceforge.pmd.testframework.SimpleAggregatorTst;
           
           /**
          + * Test for set rules.
            *
          - *
          - * @author caikang
          - * @date 2017/05/11
          + * @author shengfang.gsf
          + * @date 2016/12/13
            */
          -interface AliBaseApplicationComponent : ApplicationComponent {
          -    override fun getComponentName(): String {
          -        return "${PluginVersions.pluginId.idString}-${javaClass.name}"
          -    }
          +public class XenoAmessDeprecatedTest extends SimpleAggregatorTst {
           
          -    override fun disposeComponent() {
          -    }
          +    private static final String RULESET = "java-xenoamess-deprecated";
           
          -    override fun initComponent() {
          +    @Override
          +    public void setUp() {
          +        addRule(RULESET, "VarargsParameterRule");
               }
          -}
          \ No newline at end of file
          +}
          diff --git a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/vm/rule/other/OtherRulesTest.java b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/vm/rule/other/OtherRulesTest.java
          similarity index 94%
          rename from p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/vm/rule/other/OtherRulesTest.java
          rename to p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/vm/rule/other/OtherRulesTest.java
          index d6645df55..9462d09d0 100644
          --- a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/vm/rule/other/OtherRulesTest.java
          +++ b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/lang/vm/rule/other/OtherRulesTest.java
          @@ -13,13 +13,13 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -package com.alibaba.p3c.pmd.lang.vm.rule.other;
          +package com.xenoamess.p3c.pmd.lang.vm.rule.other;
           
           import net.sourceforge.pmd.testframework.SimpleAggregatorTst;
           
           /**
            * Test for other vm rules.
          - * 
          + *
            * @author keriezhang
            * @date 2017/06/18
            *
          diff --git a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/testframework/ExtendRuleTst.java b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/testframework/ExtendRuleTst.java
          similarity index 86%
          rename from p3c-pmd/src/test/java/com/alibaba/p3c/pmd/testframework/ExtendRuleTst.java
          rename to p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/testframework/ExtendRuleTst.java
          index 1ab0f1660..8181bc1d1 100644
          --- a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/testframework/ExtendRuleTst.java
          +++ b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/testframework/ExtendRuleTst.java
          @@ -1,10 +1,4 @@
          -package com.alibaba.p3c.pmd.testframework;
          -
          -import java.io.IOException;
          -import java.io.InputStream;
          -import java.nio.charset.Charset;
          -import java.util.ArrayList;
          -import java.util.List;
          +package com.xenoamess.p3c.pmd.testframework;
           
           import net.sourceforge.pmd.Rule;
           import net.sourceforge.pmd.testframework.RuleTst;
          @@ -12,6 +6,12 @@
           import org.apache.commons.io.IOUtils;
           import org.apache.commons.lang3.StringUtils;
           
          +import java.io.IOException;
          +import java.io.InputStream;
          +import java.nio.charset.Charset;
          +import java.util.ArrayList;
          +import java.util.List;
          +
           /**
            * @author huawen.phw
            * @date 2018/2/1
          @@ -21,25 +21,28 @@ public class ExtendRuleTst extends RuleTst {
           
           
               public void runTest(Rule rule, String examFilePath, String expectedVioLineNumbers) {
          -        TestDescriptor descriptor = extractTestsFromJavaFile(rule, examFilePath
          -            , expectedVioLineNumbers);
          +        TestDescriptor descriptor = extractTestsFromJavaFile(
          +                rule,
          +                examFilePath,
          +                expectedVioLineNumbers
          +        );
                   if (descriptor != null) {
                       runTest(descriptor);
                   }
               }
           
               /**
          -     * @param rule
          -     * @return
          +     * @param rule rule
          +     * @return TestDescriptor
                */
               public TestDescriptor extractTestsFromJavaFile(Rule rule) {
                   return extractTestsFromJavaFile(rule, "java/" + getCleanRuleName(rule) + ".java");
               }
           
               /**
          -     * @param rule
          -     * @param javaFilePath
          -     * @return
          +     * @param rule rule
          +     * @param javaFilePath javaFilePath
          +     * @return TestDescriptor
                */
               public TestDescriptor extractTestsFromJavaFile(Rule rule, String javaFilePath) {
                   return extractTestsFromJavaFile(rule, javaFilePath, "");
          @@ -72,7 +75,7 @@ public TestDescriptor extractTestsFromJavaFile(Rule rule, String javaFilePath, S
                   }
                   List expectedLineNumber = getExpectedLineNumbers(expectedLineNumbers);
                   TestDescriptor descriptor = new TestDescriptor(fileContents, rule.getDescription(),
          -            expectedLineNumber.size(), rule);
          +                expectedLineNumber.size(), rule);
                   descriptor.setExpectedLineNumbers(expectedLineNumber);
                   return descriptor;
               }
          diff --git a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/testframework/ExtendSimpleAggregatorTst.java b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/testframework/ExtendSimpleAggregatorTst.java
          similarity index 55%
          rename from p3c-pmd/src/test/java/com/alibaba/p3c/pmd/testframework/ExtendSimpleAggregatorTst.java
          rename to p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/testframework/ExtendSimpleAggregatorTst.java
          index dedc7c1d6..92097a154 100644
          --- a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/testframework/ExtendSimpleAggregatorTst.java
          +++ b/p3c-pmd/src/test/java/com/xenoamess/p3c/pmd/testframework/ExtendSimpleAggregatorTst.java
          @@ -1,6 +1,5 @@
          -package com.alibaba.p3c.pmd.testframework;
          +package com.xenoamess.p3c.pmd.testframework;
           
          -import net.sourceforge.pmd.Rule;
           import net.sourceforge.pmd.testframework.SimpleAggregatorTst;
           
           /**
          @@ -9,7 +8,7 @@
            * @date 2018/2/1
            * Description: 扩展framework,runTest支持检查.java文件
            */
          -public  class ExtendSimpleAggregatorTst extends SimpleAggregatorTst {
          +public class ExtendSimpleAggregatorTst extends SimpleAggregatorTst {
           
           
           }
          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
          deleted file mode 100644
          index 727a9790e..000000000
          --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/AvoidApacheBeanUtilsCopyRule.xml
          +++ /dev/null
          @@ -1,41 +0,0 @@
          -
          -
          -
          -	
          -	
          -
          -	
          -		Use Apache BeanUtils copy
          -		1
          -		5
          -		
          -	
          -
          -
          -	
          -	
          -	
          -		Use Spring BeanUtils copy
          -		0
          -		
          -	
          -
          -
          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/xenoamess/p3c/pmd/lang/java/rule/comment/xml/AbstractMethodOrInterfaceMethodMustUseJavadocRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/comment/xml/AbstractMethodOrInterfaceMethodMustUseJavadocRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/comment/xml/AbstractMethodOrInterfaceMethodMustUseJavadocRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/comment/xml/AvoidCommentBehindStatementRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/comment/xml/AvoidCommentBehindStatementRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/comment/xml/AvoidCommentBehindStatementRule.xml
          diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/comment/xml/ClassMustHaveAuthorRule.xml b/p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/comment/xml/ClassMustHaveAuthorRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/comment/xml/ClassMustHaveAuthorRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/comment/xml/ClassMustHaveAuthorRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/comment/xml/CommentsMustBeJavadocFormatRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/comment/xml/CommentsMustBeJavadocFormatRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/comment/xml/CommentsMustBeJavadocFormatRule.xml
          diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/comment/xml/EnumConstantsMustHaveCommentRule.xml b/p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/comment/xml/EnumConstantsMustHaveCommentRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/comment/xml/EnumConstantsMustHaveCommentRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/comment/xml/EnumConstantsMustHaveCommentRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/comment/xml/RemoveCommentedCodeRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/comment/xml/RemoveCommentedCodeRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/comment/xml/RemoveCommentedCodeRule.xml
          diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/AvoidCallStaticSimpleDateFormatRule.xml b/p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/xml/AvoidCallStaticSimpleDateFormatRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/AvoidCallStaticSimpleDateFormatRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/xml/AvoidCallStaticSimpleDateFormatRule.xml
          diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/AvoidConcurrentCompetitionRandomRule.xml b/p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/xml/AvoidConcurrentCompetitionRandomRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/AvoidConcurrentCompetitionRandomRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/xml/AvoidConcurrentCompetitionRandomRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/concurrent/xml/AvoidManuallyCreateThreadRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/AvoidManuallyCreateThreadRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/xml/AvoidManuallyCreateThreadRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/concurrent/xml/AvoidUseTimerRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/AvoidUseTimerRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/xml/AvoidUseTimerRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/concurrent/xml/CountDownShouldInFinallyRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/CountDownShouldInFinallyRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/xml/CountDownShouldInFinallyRule.xml
          diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/LockShouldWithTryFinallyRule.xml b/p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/xml/LockShouldWithTryFinallyRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/LockShouldWithTryFinallyRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/xml/LockShouldWithTryFinallyRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/concurrent/xml/ThreadLocalShouldRemoveRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/ThreadLocalShouldRemoveRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/xml/ThreadLocalShouldRemoveRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/concurrent/xml/ThreadPoolCreationRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/ThreadPoolCreationRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/xml/ThreadPoolCreationRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/concurrent/xml/ThreadShouldSetNameRule.xml
          similarity index 97%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/ThreadShouldSetNameRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/concurrent/xml/ThreadShouldSetNameRule.xml
          index da4260c14..87343b128 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/xenoamess/p3c/pmd/lang/java/rule/concurrent/xml/ThreadShouldSetNameRule.xml
          @@ -4,8 +4,8 @@
                      xsi:schemaLocation="http://pmd.sourceforge.net/rule-tests https://pmd.sourceforge.io/rule-tests_1_0_0.xsd">
               
                   ThreadShouldSetNameRule
          -        3
          -        17,19,26
          +        2
          +        17,19
                   
          +
          +    
          +         4;
          +                case 2 -> 5;
          +            };
          +        }
          +    }
          +        ]]>
          +    
          +    
          +        switch no default
          +        1
          +        4
          +        
          +    
          +
          +    
          +
          +    
          +         4;
          +                case 2 -> 5;
          +                default -> 6;
          +            };
          +        }
          +    }
          +        ]]>
          +    
          +    
          +        switch have default
          +        0
          +        
          +    
          +
          +    
          +
          +    
          +         {
          +                }
          +                case 2 -> {
          +                }
          +                default -> {
          +                }
          +            };
          +        }
          +    }
          +        ]]>
          +    
          +    
          +        switch have default
          +        0
          +        
          +    
          +
          +
          \ No newline at end of file
          diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/xml/SwitchStatementRule.xml b/p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/flowcontrol/xml/SwitchStatementRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/xml/SwitchStatementRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/flowcontrol/xml/SwitchStatementRule.xml
          diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/AbstractClassShouldStartWithAbstractNamingRule.xml b/p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/naming/xml/AbstractClassShouldStartWithAbstractNamingRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/AbstractClassShouldStartWithAbstractNamingRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/naming/xml/AbstractClassShouldStartWithAbstractNamingRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/naming/xml/ArrayNamingShouldHaveBracketRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/ArrayNamingShouldHaveBracketRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/naming/xml/ArrayNamingShouldHaveBracketRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/naming/xml/AvoidStartWithDollarAndUnderLineNamingRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/AvoidStartWithDollarAndUnderLineNamingRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/naming/xml/AvoidStartWithDollarAndUnderLineNamingRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/naming/xml/BooleanPropertyShouldNotStartWithIsRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/BooleanPropertyShouldNotStartWithIsRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/naming/xml/BooleanPropertyShouldNotStartWithIsRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/naming/xml/ClassNamingShouldBeCamelRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/ClassNamingShouldBeCamelRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/naming/xml/ClassNamingShouldBeCamelRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/naming/xml/ConstantFieldShouldBeUpperCaseRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/ConstantFieldShouldBeUpperCaseRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/naming/xml/ConstantFieldShouldBeUpperCaseRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/naming/xml/ExceptionClassShouldEndWithExceptionRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/ExceptionClassShouldEndWithExceptionRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/naming/xml/ExceptionClassShouldEndWithExceptionRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/naming/xml/LowerCamelCaseVariableNamingRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/LowerCamelCaseVariableNamingRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/naming/xml/LowerCamelCaseVariableNamingRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/naming/xml/PackageNamingRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/PackageNamingRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/naming/xml/PackageNamingRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/naming/xml/ServiceOrDaoClassShouldEndWithImplRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/ServiceOrDaoClassShouldEndWithImplRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/naming/xml/ServiceOrDaoClassShouldEndWithImplRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/naming/xml/TestClassShouldEndWithTestNamingRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/TestClassShouldEndWithTestNamingRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/naming/xml/TestClassShouldEndWithTestNamingRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/oop/xml/BigDecimalAvoidDoubleConstructorRule.xml
          similarity index 59%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/BigDecimalAvoidDoubleConstructorRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/oop/xml/BigDecimalAvoidDoubleConstructorRule.xml
          index 2256365f7..23e45d780 100644
          --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/BigDecimalAvoidDoubleConstructorRule.xml
          +++ b/p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/oop/xml/BigDecimalAvoidDoubleConstructorRule.xml
          @@ -3,7 +3,7 @@
                      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                      xsi:schemaLocation="http://pmd.sourceforge.net/rule-tests https://pmd.sourceforge.io/rule-tests_1_0_0.xsd">
           
          -    
          +    
                   
               
               
          -        BigDicimal initializer allocation
          +        BigDecimal initializer allocation
                   2
                   3,8
          -        
          +        
          +    
          +
          +    
          +        
          +    
          +    
          +        BigDecimal initializer allocation
          +        0
          +        
               
           
           
          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/xenoamess/p3c/pmd/lang/java/rule/oop/xml/EqualsAvoidNullRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/EqualsAvoidNullRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/oop/xml/EqualsAvoidNullRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/oop/xml/PojoMustOverrideToStringRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/PojoMustOverrideToStringRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/oop/xml/PojoMustOverrideToStringRule.xml
          diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/PojoMustUsePrimitiveFieldRule.xml b/p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/oop/xml/PojoMustUsePrimitiveFieldRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/PojoMustUsePrimitiveFieldRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/oop/xml/PojoMustUsePrimitiveFieldRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/oop/xml/PojoNoDefaultValueRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/PojoNoDefaultValueRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/oop/xml/PojoNoDefaultValueRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/oop/xml/StringConcatRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/StringConcatRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/oop/xml/StringConcatRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/oop/xml/WrapperTypeEqualityRule.xml
          similarity index 94%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/WrapperTypeEqualityRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/oop/xml/WrapperTypeEqualityRule.xml
          index cee259d77..5e66b15ea 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/xenoamess/p3c/pmd/lang/java/rule/oop/xml/WrapperTypeEqualityRule.xml
          @@ -30,8 +30,8 @@
                       if (a == Integer.MAX_VALUE) {    // BAD
                           // do nothing
                       }
          -            // PMD can not resolve type of Inner.FLAG
          -            if (a == Inner.FLAG) {
          +            // PMD can resolve type of Inner.FLAG since 6.42.0
          +            if (a == Inner.FLAG) {    // BAD
                           // do nothing
                       }
                       // After upgrade pmd version, can resolve
          @@ -51,8 +51,8 @@
               
               
                   compare wrapper type objects without equals
          -        4
          -        11,23,31,34
          +        5
          +        11,23,27,31,34
                   
               
           
          @@ -60,7 +60,7 @@
           
               
                   
               
                   expression is primitive type
          -        1
          -        17
          +        0
                   
               
               
          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/xenoamess/p3c/pmd/lang/java/rule/orm/xml/IbatisMethodQueryForListRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/orm/xml/IbatisMethodQueryForListRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/orm/xml/IbatisMethodQueryForListRule.xml
          diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/java/UseRightCaseForDateFormatRuleExam.java b/p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/other/java/UseRightCaseForDateFormatRuleExam.java
          similarity index 96%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/java/UseRightCaseForDateFormatRuleExam.java
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/other/java/UseRightCaseForDateFormatRuleExam.java
          index f11d0ff26..7a8b6be1d 100644
          --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/java/UseRightCaseForDateFormatRuleExam.java
          +++ b/p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/other/java/UseRightCaseForDateFormatRuleExam.java
          @@ -1,4 +1,4 @@
          -package com.alibaba.p3c.pmd.lang.java.rule.other.java;
          +package com.xenoamess.p3c.pmd.lang.java.rule.other.java;
           
           import java.text.SimpleDateFormat;
           
          diff --git a/p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/other/xml/AvoidApacheBeanUtilsCopyRule.xml b/p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/other/xml/AvoidApacheBeanUtilsCopyRule.xml
          new file mode 100644
          index 000000000..fd48b92a8
          --- /dev/null
          +++ b/p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/other/xml/AvoidApacheBeanUtilsCopyRule.xml
          @@ -0,0 +1,91 @@
          +
          +
          +
          +    
          +
          +    
          +    
          +
          +    
          +        Use Apache BeanUtils copy
          +        1
          +        5
          +        
          +    
          +
          +    
          +    
          +
          +    
          +        Use Apache BeanUtils copy
          +        1
          +        4
          +        
          +    
          +
          +    
          +    
          +
          +    
          +        Use Apache BeanUtils other
          +        0
          +        
          +    
          +
          +    
          +    
          +    
          +        Use Spring BeanUtils copy
          +        0
          +        
          +    
          +
          +    
          +    
          +
          +    
          +        Use Not Apache BeanUtils copy
          +        0
          +        
          +    
          +
          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/xenoamess/p3c/pmd/lang/java/rule/other/xml/AvoidDoubleOrFloatEqualCompareRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/AvoidDoubleOrFloatEqualCompareRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/other/xml/AvoidDoubleOrFloatEqualCompareRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/other/xml/AvoidMissUseOfMathRandomRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/AvoidMissUseOfMathRandomRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/other/xml/AvoidMissUseOfMathRandomRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/other/xml/AvoidNewDateGetTimeRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/AvoidNewDateGetTimeRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/other/xml/AvoidNewDateGetTimeRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/other/xml/AvoidPatternCompileInMethodRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/AvoidPatternCompileInMethodRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/other/xml/AvoidPatternCompileInMethodRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/other/xml/MethodTooLongRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/MethodTooLongRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/other/xml/MethodTooLongRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/other/xml/UseRightCaseForDateFormatRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/UseRightCaseForDateFormatRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/other/xml/UseRightCaseForDateFormatRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/set/xml/ClassCastExceptionWithSubListToArrayListRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/ClassCastExceptionWithSubListToArrayListRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/set/xml/ClassCastExceptionWithSubListToArrayListRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/set/xml/ClassCastExceptionWithToArrayRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/ClassCastExceptionWithToArrayRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/set/xml/ClassCastExceptionWithToArrayRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/set/xml/CollectionInitShouldAssignCapacityRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/CollectionInitShouldAssignCapacityRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/set/xml/CollectionInitShouldAssignCapacityRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/set/xml/ConcurrentExceptionWithModifyOriginSubListRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/ConcurrentExceptionWithModifyOriginSubListRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/set/xml/ConcurrentExceptionWithModifyOriginSubListRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/set/xml/DontModifyInForeachCircleRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/DontModifyInForeachCircleRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/set/xml/DontModifyInForeachCircleRule.xml
          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/xenoamess/p3c/pmd/lang/java/rule/set/xml/UnsupportedExceptionWithModifyAsListRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/UnsupportedExceptionWithModifyAsListRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/set/xml/UnsupportedExceptionWithModifyAsListRule.xml
          diff --git a/p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/xenoamess/additional/xml/EqualsHashCodeRule.xml b/p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/xenoamess/additional/xml/EqualsHashCodeRule.xml
          new file mode 100644
          index 000000000..f6c5306cd
          --- /dev/null
          +++ b/p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/xenoamess/additional/xml/EqualsHashCodeRule.xml
          @@ -0,0 +1,96 @@
          +
          +
          +
          +    
          +    
          +
          +    
          +        sets-EqualsHashCodeRule-ok.
          +        0
          +        
          +    
          +
          +    
          +    
          +
          +    
          +        sets-EqualsHashCodeRule-missHashCodeWarn.
          +        1
          +        5
          +        
          +    
          +
          +    
          +    
          +
          +    
          +        sets-EqualsHashCodeRule-missEqualsWarn.
          +        1
          +        5
          +        
          +    
          +
          +    
          +    
          +
          +    
          +        shall ignore abstract class.
          +        0
          +        
          +    
          +
          diff --git a/p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/xenoamess/additional/xml/SneakyThrowsWithoutExceptionTypeRule.xml b/p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/xenoamess/additional/xml/SneakyThrowsWithoutExceptionTypeRule.xml
          new file mode 100644
          index 000000000..b8d1a08e3
          --- /dev/null
          +++ b/p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/xenoamess/additional/xml/SneakyThrowsWithoutExceptionTypeRule.xml
          @@ -0,0 +1,134 @@
          +
          +
          +
          +    
          +    
          +
          +    
          +        testFail1
          +        1
          +        4
          +        
          +    
          +
          +    
          +    
          +
          +    
          +        testFail2
          +        1
          +        4
          +        
          +    
          +
          +    
          +    
          +
          +    
          +        testFail3
          +        1
          +        4
          +        
          +    
          +
          +    
          +    
          +
          +    
          +        testFail4
          +        1
          +        2
          +        
          +    
          +
          +    
          +    
          +
          +    
          +        testSucceed1
          +        0
          +        
          +    
          +
          +    
          +    
          +
          +    
          +        testSucceed2
          +        0
          +        
          +    
          +
          +    
          +    
          +
          +    
          +        testSucceed3
          +        0
          +        
          +    
          +
          +
          diff --git a/p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/xenoamess/deprecated/xml/VarargsParameterRule.xml b/p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/xenoamess/deprecated/xml/VarargsParameterRule.xml
          new file mode 100644
          index 000000000..0db9bf1e7
          --- /dev/null
          +++ b/p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/java/rule/xenoamess/deprecated/xml/VarargsParameterRule.xml
          @@ -0,0 +1,27 @@
          +
          +
          +
          +    
          +        
          +    
          +    
          +        varargs-with-object-type
          +        1
          +        2
          +        
          +    
          +
          +
          +    
          +
          \ 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/xenoamess/p3c/pmd/lang/vm/rule/other/xml/UseQuietReferenceNotationRule.xml
          similarity index 100%
          rename from p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/vm/rule/other/xml/UseQuietReferenceNotationRule.xml
          rename to p3c-pmd/src/test/resources/com/xenoamess/p3c/pmd/lang/vm/rule/other/xml/UseQuietReferenceNotationRule.xml
          diff --git a/p3c_config.x8l b/p3c_config.x8l
          new file mode 100644
          index 000000000..b64393e57
          --- /dev/null
          +++ b/p3c_config.x8l
          @@ -0,0 +1,5 @@
          +
          +    
          +        VarargsParameterRule>
          +    >
          +>
          diff --git a/sonar.cmd b/sonar.cmd
          new file mode 100644
          index 000000000..fdeb02f87
          --- /dev/null
          +++ b/sonar.cmd
          @@ -0,0 +1,33 @@
          +cd ./p3c-pmd
          +call mvn clean install -Dmaven.javadoc.skip=false -e -X -Psonatype-oss-release
          +call mvn sonar:sonar ^
          +-Dsonar.scm.exclusions.disabled=true ^
          +-Dsonar.projectKey=p3c-cmd ^
          +-Dsonar.organization=xenoamess-github ^
          +-Dsonar.host.url=https://sonarcloud.io ^
          +-Dsonar.log.level=DEBUG ^
          +-Dsonar.language=java ^
          +-Dsonar.java.source=1.8 ^
          +-Dsonar.sourceEncoding=UTF-8 ^
          +-Dsonar.java.binaries=target/classes/ ^
          +-Dsonar.java.test.binaries=target/test-classes/ ^
          +-Dsonar.java.coveragePlugin=jacoco ^
          +-Dsonar.jacoco.reportPaths=target/jacoco.exec ^
          +-Dsonar.junit.reportPaths=target/surefire-reports/ ^
          +-Dsonar.login=353821de77c27c633a2b3339a9cfc5ad08d66086
          +
          +cd ../
          +cd ./idea-plugin
          +
          +cd ./p3c-common
          +call ../gradlew publishToMavenLocal sonarqube
          +cd ../
          +
          +cd ./p3c-idea
          +rem call ../gradlew publishToMavenLocal
          +cd ../
          +
          +rem call ./gradlew buildPlugin sonarqube
          +
          +cd ../
          +pause