01: package abbot.util;
02:
03: import java.lang.reflect.Array;
04:
05: /** Utility class to perform comparisons. */
06: public class ExtendedComparator {
07: private ExtendedComparator() {
08: }
09:
10: /** Match with a regexp if the pattern contains a ".*" or is bounded by
11: * slashes (/regexp/). Multiline matches are enabled by /(?m)regexp/.
12: * Embedded newlines ("\n") in the match string will then match
13: * end-of-lines.
14: */
15: // Requiring exact matches eliminates the need to always include the start
16: // "^" and finish "$" symbols.
17: public static boolean stringsMatch(String pattern, String actual) {
18: if (pattern.startsWith("/")
19: && pattern.substring(1).endsWith("/")) {
20: pattern = pattern.substring(1, pattern.length() - 1);
21: return Regexp.stringMatch(pattern, actual);
22: }
23: if (pattern.indexOf(".*") != -1) {
24: return Regexp.stringMatch(pattern, actual);
25: }
26: return pattern.equals(actual);
27: }
28:
29: /** Perform element-by-element comparisons of arrays in addition to
30: regular comparisons. */
31: public static boolean equals(Object obj1, Object obj2) {
32: boolean result = false;
33: if (obj1 == null && obj2 == null) {
34: result = true;
35: } else if (obj1 == null && obj2 != null || obj2 == null
36: && obj1 != null) {
37: result = false;
38: } else if (obj1.equals(obj2)) {
39: result = true;
40: }
41: // If both are strings, check for a regexp match
42: else if (obj1 instanceof String && obj2 instanceof String) {
43: result = stringsMatch((String) obj1, (String) obj2);
44: } else if (obj1.getClass().isArray()
45: && obj2.getClass().isArray()) {
46: if (Array.getLength(obj1) == Array.getLength(obj2)) {
47: result = true;
48: for (int i = 0; i < Array.getLength(obj1); i++) {
49: if (!equals(Array.get(obj1, i), Array.get(obj2, i))) {
50: result = false;
51: break;
52: }
53: }
54: }
55: }
56: return result;
57: }
58: }
|