1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sourceforge.domian.specification;
17
18
19 import java.util.regex.Pattern;
20 import java.util.regex.PatternSyntaxException;
21
22 import org.apache.commons.lang.Validate;
23 import org.apache.commons.lang.builder.EqualsBuilder;
24 import org.apache.commons.lang.builder.HashCodeBuilder;
25 import org.slf4j.Logger;
26
27 import static java.lang.Boolean.FALSE;
28 import static org.slf4j.LoggerFactory.getLogger;
29
30
31
32
33
34
35
36
37
38 class RegularExpressionMatcherStringSpecification extends AbstractSpecification<String> implements ValueBoundSpecification<String> {
39
40 private static final Logger log = getLogger(RegularExpressionMatcherStringSpecification.class);
41
42 protected Pattern compiledRegularExpression;
43
44 RegularExpressionMatcherStringSpecification(final String regularExpression) {
45 Validate.notNull(regularExpression, "Regular expression parameter cannot be null");
46 this.compiledRegularExpression = compileRegexPattern(regularExpression);
47 }
48
49 protected Pattern compileRegexPattern(final String regularExpression) {
50 try {
51 return Pattern.compile(regularExpression, Pattern.UNICODE_CASE);
52
53 } catch (PatternSyntaxException e) {
54 throw new IllegalArgumentException("Illegal regex expression parameter: " + e.getMessage());
55 }
56 }
57
58 @Override
59 public String getValue() {
60 return this.compiledRegularExpression.pattern();
61 }
62
63 @Override
64 public Boolean isSatisfiedBy(final String candidate) {
65 return candidate != null && compiledRegularExpression.matcher(candidate).matches();
66 }
67
68 @Override
69 public Boolean isDisjointWith(final Specification<?> specification) {
70 log.warn("isDisjointWith() is not implemented (intractable!?) for regex specifications - assuming NOT disjoint");
71 return FALSE;
72 }
73
74 @Override
75 public int hashCode() {
76 return new HashCodeBuilder(4877, 8555).append(this.getValue()).toHashCode();
77 }
78
79 @Override
80 public boolean equals(Object otherObject) {
81 if (otherObject == null) { return false; }
82 if (!(otherObject instanceof RegularExpressionMatcherStringSpecification)) { return false; }
83 return new EqualsBuilder()
84 .append(this.getValue(), ((RegularExpressionMatcherStringSpecification) otherObject).getValue())
85 .isEquals();
86 }
87 }