Functional PathPattern comparator
This commit is contained in:
parent
ef175d7ca6
commit
8c4b1ab781
|
|
@ -692,44 +692,22 @@ public class PathPattern implements Comparable<PathPattern> {
|
|||
}
|
||||
|
||||
|
||||
public static final Comparator<PathPattern> SPECIFICITY_COMPARATOR = (p1, p2) -> {
|
||||
// Same object or null == null?
|
||||
if (p1 == p2) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// null is sorted last
|
||||
if (p2 == null) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
// catchall patterns are sorted last. If both catchall then the
|
||||
// length is considered
|
||||
if (p1.isCatchAll()) {
|
||||
if (p2.isCatchAll()) {
|
||||
int lenDifference = p1.getNormalizedLength() - p2.getNormalizedLength();
|
||||
if (lenDifference != 0) {
|
||||
return (lenDifference < 0) ? +1 : -1;
|
||||
}
|
||||
}
|
||||
else {
|
||||
return +1;
|
||||
}
|
||||
}
|
||||
else if (p2.isCatchAll()) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
// This will sort such that if they differ in terms of wildcards or
|
||||
// captured variable counts, the one with the most will be sorted last
|
||||
int score = p1.getScore() - p2.getScore();
|
||||
if (score != 0) {
|
||||
return (score < 0) ? -1 : +1;
|
||||
}
|
||||
|
||||
// longer is better
|
||||
int lenDifference = p1.getNormalizedLength() - p2.getNormalizedLength();
|
||||
return Integer.compare(0, lenDifference);
|
||||
};
|
||||
|
||||
/**
|
||||
* Comparator that sorts patterns by specificity as follows:
|
||||
* <ol>
|
||||
* <li>Null instances are last.
|
||||
* <li>Catch-all patterns are last.
|
||||
* <li>If both patterns are catch-all, consider the length (longer wins).
|
||||
* <li>Compare wildcard and captured variable count (lower wins).
|
||||
* <li>Consider length (longer wins)
|
||||
* </ol>
|
||||
*/
|
||||
public static final Comparator<PathPattern> SPECIFICITY_COMPARATOR =
|
||||
Comparator.nullsLast(
|
||||
Comparator.<PathPattern>
|
||||
comparingInt(p -> p.isCatchAll() ? 1 : 0)
|
||||
.thenComparingInt(p -> p.isCatchAll() ? -1 * p.getNormalizedLength() : 0)
|
||||
.thenComparing(PathPattern::getScore)
|
||||
.thenComparingInt(p -> -1 * p.getNormalizedLength())
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -967,10 +967,10 @@ public class PathPatternTests {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void patternCompareToNull() {
|
||||
PathPatternParser p = new PathPatternParser();
|
||||
PathPattern pp = p.parse("/abc");
|
||||
assertEquals(-1, pp.compareTo(null));
|
||||
public void patternCompareWithNull() {
|
||||
assertTrue(PathPattern.SPECIFICITY_COMPARATOR.compare(null, null) == 0);
|
||||
assertTrue(PathPattern.SPECIFICITY_COMPARATOR.compare(parse("/abc"), null) < 0);
|
||||
assertTrue(PathPattern.SPECIFICITY_COMPARATOR.compare(null, parse("/abc")) > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
|
|||
Loading…
Reference in New Issue