3 * Copyright (C) 2009 EDIT
4 * European Distributed Institute of Taxonomy
5 * http://www.e-taxonomy.eu
7 * The contents of this file are subject to the Mozilla Public License Version 1.1
8 * See LICENSE.TXT at the top of this package for the full license terms.
10 package eu
.etaxonomy
.cdm
.model
.common
;
12 import java
.util
.Comparator
;
13 import java
.util
.HashMap
;
15 import java
.util
.regex
.Pattern
;
17 import org
.springframework
.stereotype
.Component
;
19 import eu
.etaxonomy
.cdm
.model
.taxon
.TaxonNode
;
22 * Abstract Comparator for Strings which allows define substitution rules which
23 * are applied to the String to be compared before the actual comparison takes
24 * place. By this it is e.g. possible to influence the position of objects in sorted lists etc.
26 * <b>Intended usage</b>: To allow maximum flexibility the property
27 * {@link #setSubstitutionRules(Map)} should be set in the spring application
30 * @author a.kohlbecker
34 public abstract class AbstractStringComparator
implements Comparator
<TaxonNode
> {
36 protected Map
<Pattern
, String
> substitutionRules
= null;
39 * Set the private field substitutionRules. The substitutionRules consist of
40 * a regular expression as key and a string to be prepended as value.
44 public void setSubstitutionRules(Map
<String
, String
> substitutionRules
) {
45 this.substitutionRules
= new HashMap
<Pattern
, String
>(substitutionRules
.size());
46 for (String regex
: substitutionRules
.keySet()) {
47 this.substitutionRules
.put(Pattern
.compile(regex
), substitutionRules
.get(regex
));
53 * Applies the first matching <code>substitutionRules</code> set by
54 * {@link #setSubstitutionRules()} to the given String. A rules is applied
55 * in the following way: If the regular expression matches the given string
56 * <code>s</code> the String mapped by the regular expression is prepended
62 protected String
applySubstitutionRules(String s
) {
63 if (substitutionRules
== null) {
66 StringBuffer sb
= new StringBuffer();
67 for (Pattern pattern
: substitutionRules
.keySet()) {
68 if (pattern
.matcher(s
).matches()) {
69 sb
.append(substitutionRules
.get(pattern
)).append(s
);