merge hibernate4 migration branch into trunk
[cdmlib.git] / cdmlib-model / src / main / java / eu / etaxonomy / cdm / model / common / AbstractStringComparator.java
1 // $Id$
2 /**
3 * Copyright (C) 2009 EDIT
4 * European Distributed Institute of Taxonomy
5 * http://www.e-taxonomy.eu
6 *
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.
9 */
10 package eu.etaxonomy.cdm.model.common;
11
12 import java.util.Comparator;
13 import java.util.HashMap;
14 import java.util.Map;
15 import java.util.regex.Pattern;
16
17 import org.springframework.stereotype.Component;
18
19 import eu.etaxonomy.cdm.model.taxon.TaxonNode;
20
21 /**
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.
25 * <p>
26 * <b>Intended usage</b>: To allow maximum flexibility the property
27 * {@link #setSubstitutionRules(Map)} should be set in the spring application
28 * context.
29 *
30 * @author a.kohlbecker
31 * @date 24.06.2009
32 */
33 @Component
34 public abstract class AbstractStringComparator implements Comparator<TaxonNode> {
35
36 protected Map<Pattern, String> substitutionRules = null;
37
38 /**
39 * Set the private field substitutionRules. The substitutionRules consist of
40 * a regular expression as key and a string to be prepended as value.
41 *
42 * @param rules
43 */
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));
48 }
49
50 }
51
52 /**
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
57 * to <code>s</code>.
58 *
59 * @param s
60 * @return
61 */
62 protected String applySubstitutionRules(String s) {
63 if (substitutionRules == null) {
64 return s;
65 }
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);
70 return sb.toString();
71 }
72
73 }
74 return s;
75 }
76
77 }