1
|
/**
|
2
|
* Copyright (C) 2009 EDIT
|
3
|
* European Distributed Institute of Taxonomy
|
4
|
* http://www.e-taxonomy.eu
|
5
|
*
|
6
|
* The contents of this file are subject to the Mozilla Public License Version 1.1
|
7
|
* See LICENSE.TXT at the top of this package for the full license terms.
|
8
|
*/
|
9
|
package eu.etaxonomy.cdm.common;
|
10
|
|
11
|
import java.util.Comparator;
|
12
|
import java.util.HashMap;
|
13
|
import java.util.Map;
|
14
|
import java.util.regex.Pattern;
|
15
|
|
16
|
/**
|
17
|
* Abstract Comparator for Strings which allows define substitution rules which
|
18
|
* are applied to the String to be compared before the actual comparison takes
|
19
|
* place. By this it is e.g. possible to influence the position of objects in sorted lists etc.
|
20
|
* <p>
|
21
|
* <b>Intended usage</b>: To allow maximum flexibility the property
|
22
|
* {@link #setSubstitutionRules(Map)} should be set in the spring application
|
23
|
* context.
|
24
|
*
|
25
|
* @author a.kohlbecker
|
26
|
* @since 24.06.2009
|
27
|
*/
|
28
|
public abstract class AbstractStringComparator<T extends Object> implements Comparator<T> {
|
29
|
|
30
|
protected Map<Pattern, String> substitutionRules = null;
|
31
|
|
32
|
/**
|
33
|
* Set the private field substitutionRules. The substitutionRules consist of
|
34
|
* a regular expression as key and a string to be prepended as value.
|
35
|
*/
|
36
|
public void setSubstitutionRules(Map<String, String> substitutionRules) {
|
37
|
this.substitutionRules = new HashMap<Pattern, String>(substitutionRules.size());
|
38
|
for (String regex : substitutionRules.keySet()) {
|
39
|
this.substitutionRules.put(Pattern.compile(regex), substitutionRules.get(regex));
|
40
|
}
|
41
|
}
|
42
|
|
43
|
/**
|
44
|
* Applies the first matching <code>substitutionRules</code> set by
|
45
|
* {@link #setSubstitutionRules()} to the given String. A rules is applied
|
46
|
* in the following way: If the regular expression matches the given string
|
47
|
* <code>s</code> the String mapped by the regular expression is prepended
|
48
|
* to <code>s</code>.
|
49
|
*
|
50
|
* @param s
|
51
|
* @return
|
52
|
*/
|
53
|
protected String applySubstitutionRules(String s) {
|
54
|
if (substitutionRules == null) {
|
55
|
return s;
|
56
|
}
|
57
|
StringBuffer sb = new StringBuffer();
|
58
|
for (Pattern pattern : substitutionRules.keySet()) {
|
59
|
if (pattern.matcher(s).matches()) {
|
60
|
sb.append(substitutionRules.get(pattern)).append(s);
|
61
|
return sb.toString();
|
62
|
}
|
63
|
|
64
|
}
|
65
|
return s;
|
66
|
}
|
67
|
|
68
|
}
|