There is lots of duplicates codes including:
Duplicates within file
Duplicates within package
Duplicates around multiple packages
Duplicates around separate Maven Modules
Is there any way to find duplicate codes using Netbeans 8+ or Netbeans Plugins or Maven Plugin with Netbeans or Standalone tools similar to Intellij?
I am unable to find documentation of same.
I have found PMD in Maven but unable to link with Netbeans 8.2 and We are only supposed to use Netbeans
You can find duplicated code for a NetBeans Maven project using the Apache Maven PMD Plugin. Simply add the following to your project's pom.xml:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<version>2.7.1</version>
<executions>
<execution>
<goals>
<goal>check</goal>
<goal>cpd-check</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<version>2.7.1</version>
</plugin>
</plugins>
</reporting>
When you build your project PMD's copy paste detector (CPD) will be run, and write its results to file {project directory}\target\cpd.xml. If no duplication is found that file looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<pmd-cpd>
</pmd-cpd>
However, if duplication is found the file looks similar to this:
<?xml version="1.0" encoding="UTF-8"?>
<pmd-cpd>
<duplication lines="162" tokens="608">
<file line="95" path="D:\NetBeansProjectsJava9\checkduplication\src\main\java\com\unthreading\checkduplication\ParseJavadoc.java"/>
<file line="258" path="D:\NetBeansProjectsJava9\checkduplication\src\main\java\com\unthreading\checkduplication\ParseJavadoc.java"/>
<codefragment>
<![CDATA[
...details of the duplicated code....
]]>
</codefragment>
</duplication>
</pmd-cpd>
After updating the POM as described above, a very simple way to verify that duplication detection is working is to copy/paste a large method within some class, and then give the pasted method another name so that the code still compiles. I tried that and got the following result in the Output window:
maven-pmd-plugin:2.7.1:cpd-check (default) @ checkduplication ---
BUILD FAILURE
Total time: 2.689 s Finished at: 2018-02-15T17:06:23-05:00 Final Memory: 20M/70M
Failed to execute goal org.apache.maven.plugins:maven-pmd-plugin:2.7.1:cpd-check (default) on project checkduplication: You have 1 CPD duplication. For more details see:D:\NetBeansProjectsJava9\checkduplication\target\cpd.xml -> [Help 1]
A couple of final points:
Specifying <goal>cpd-check</goal>
(as I did) causes the build to fail when duplication is detected, but alternative goals can be specified.
There are more recent versions of maven-pmd-plugin than 2.7.1, but that is the most recent version where copy/paste detection works out of the box. More recent versions may work after playing with the configuration, but I didn't try that.