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
.api
.service
;
12 import java
.util
.Comparator
;
13 import java
.util
.HashMap
;
15 import java
.util
.regex
.Matcher
;
16 import java
.util
.regex
.Pattern
;
18 import org
.springframework
.stereotype
.Component
;
20 import eu
.etaxonomy
.cdm
.model
.taxon
.TaxonNode
;
23 * Abstract Comparator for Strings which allows define substitution rules which
24 * are applied to the String to be compared before the actual comparison takes
25 * place. By this it is e.g. possible to influence the position of objects in sorted lists etc.
27 * <b>Intended usage</b>: To allow maximum flexibility the property
28 * {@link #setSubstitutionRules(Map)} should be set in the spring application
31 * @author a.kohlbecker
35 public abstract class AbstractStringComparator
implements Comparator
<TaxonNode
> {
37 protected Map
<Pattern
, String
> substitutionRules
= null;
40 * Set the private field substitutionRules. The substitutionRules consist of
41 * a regular expression as key and a string to be prepended as value.
45 public void setSubstitutionRules(Map
<String
, String
> substitutionRules
) {
46 this.substitutionRules
= new HashMap
<Pattern
, String
>(substitutionRules
.size());
47 for (String regex
: substitutionRules
.keySet()) {
48 this.substitutionRules
.put(Pattern
.compile(regex
), substitutionRules
.get(regex
));
54 * Applies the first matching <code>substitutionRules</code> set by
55 * {@link #setSubstitutionRules()} to the given String. A rules is applied
56 * in the following way: If the regular expression matches the given string
57 * <code>s</code> the String mapped by the regular expression is prepended
63 protected String
applySubstitutionRules(String s
) {
64 if (substitutionRules
== null) {
67 StringBuffer sb
= new StringBuffer();
68 for (Pattern pattern
: substitutionRules
.keySet()) {
69 if (pattern
.matcher(s
).matches()) {
70 sb
.append(substitutionRules
.get(pattern
)).append(s
);