Project

General

Profile

Download (2.26 KB) Statistics
| Branch: | Tag: | Revision:
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
	 * @param rules
37
	 */
38
	public void setSubstitutionRules(Map<String, String> substitutionRules) {
39
		this.substitutionRules = new HashMap<Pattern, String>(substitutionRules.size());
40
		for (String regex : substitutionRules.keySet()) {
41
			this.substitutionRules.put(Pattern.compile(regex), substitutionRules.get(regex));
42
		}
43

    
44
	}
45

    
46
	/**
47
	 * Applies the first matching <code>substitutionRules</code> set by
48
	 * {@link #setSubstitutionRules()} to the given String. A rules is applied
49
	 * in the following way: If the regular expression matches the given string
50
	 * <code>s</code> the String mapped by the regular expression is prepended
51
	 * to <code>s</code>.
52
	 * 
53
	 * @param s
54
	 * @return
55
	 */
56
	protected String applySubstitutionRules(String s) {
57
		if (substitutionRules == null) {
58
			return s;
59
		}
60
		StringBuffer sb = new StringBuffer();
61
		for (Pattern pattern : substitutionRules.keySet()) {
62
			if (pattern.matcher(s).matches()) {
63
				sb.append(substitutionRules.get(pattern)).append(s);
64
				return sb.toString();
65
			}
66

    
67
		}
68
		return s;
69
	}
70

    
71
}
(1-1/23)