RuleViolationComparator.java
01 /**
02  * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
03  */
04 package net.sourceforge.pmd;
05 
06 import java.util.Comparator;
07 
08 /**
09  * Compares RuleViolations using the following criteria:
10  <ol>
11  *    <li>Source file name</li>
12  *    <li>Begin line</li>
13  *    <li>Description</li>
14  *    <li>Begin column</li>
15  *    <li>End line</li>
16  *    <li>End column</li>
17  *    <li>Rule name</li>
18  </ol>
19  */
20 public final class RuleViolationComparator implements Comparator<RuleViolation> {
21 
22     public static final RuleViolationComparator INSTANCE = new RuleViolationComparator();
23 
24     private RuleViolationComparator() {
25     }
26 
27     public int compare(final RuleViolation r1, final RuleViolation r2) {
28   int cmp = r1.getFilename().compareTo(r2.getFilename());
29   if (cmp == 0) {
30       cmp = r1.getBeginLine() - r2.getBeginLine();
31       if (cmp == 0) {
32     cmp = compare(r1.getDescription(), r2.getDescription());
33     if (cmp == 0) {
34         cmp = r1.getBeginColumn() - r2.getBeginColumn();
35         if (cmp == 0) {
36       cmp = r1.getEndLine() - r2.getEndLine();
37       if (cmp == 0) {
38           cmp = r1.getEndColumn() - r2.getEndColumn();
39           if (cmp == 0) {
40         cmp = r1.getRule().getName().compareTo(r2.getRule().getName());
41           }
42       }
43         }
44     }
45       }
46   }
47   return cmp;
48     }
49 
50     private static int compare(final String s1, final String s2) {
51   // Treat null as larger
52   if (s1 == null) {
53       return 1;
54   else if (s2 == null) {
55       return -1;
56   else {
57       return s1.compareTo(s2);
58   }
59     }
60 }