1 package org.apache.turbine.services.intake.validator; 2 3 18 19 import java.util.Map ; 20 21 import org.apache.commons.lang.StringUtils; 22 23 import org.apache.oro.text.regex.MalformedPatternException; 24 import org.apache.oro.text.regex.Pattern; 25 import org.apache.oro.text.regex.Perl5Compiler; 26 import org.apache.oro.text.regex.Perl5Matcher; 27 28 46 public class StringValidator 47 extends DefaultValidator 48 { 49 50 protected String maskString = null; 51 52 53 protected Pattern maskPattern = null; 54 55 56 protected String maskMessage = null; 57 58 59 67 public StringValidator(Map paramMap) 68 throws InvalidMaskException 69 { 70 init(paramMap); 71 } 72 73 76 public StringValidator() 77 { 78 } 79 80 88 public void init(Map paramMap) 89 throws InvalidMaskException 90 { 91 super.init(paramMap); 92 93 Constraint constraint = (Constraint) paramMap.get(MASK_RULE_NAME); 94 if (constraint != null) 95 { 96 String param = constraint.getValue(); 97 setMask(param); 98 maskMessage = constraint.getMessage(); 99 } 100 101 } 102 103 110 public boolean isValid(String testValue) 111 { 112 boolean valid = false; 113 try 114 { 115 assertValidity(testValue); 116 valid = true; 117 } 118 catch (ValidationException ve) 119 { 120 valid = false; 121 } 122 return valid; 123 } 124 125 133 public void assertValidity(String testValue) 134 throws ValidationException 135 { 136 super.assertValidity(testValue); 137 138 if (required || StringUtils.isNotEmpty(testValue)) 139 { 140 if (maskPattern != null) 141 { 142 143 Perl5Matcher patternMatcher = new Perl5Matcher(); 144 145 boolean patternMatch = 146 patternMatcher.matches(testValue, maskPattern); 147 148 log.debug("Trying to match " + testValue 149 + " to pattern " + maskString); 150 151 if (!patternMatch) 152 { 153 errorMessage = maskMessage; 154 throw new ValidationException(maskMessage); 155 } 156 } 157 } 158 } 159 160 164 169 public String getMask() 170 { 171 return maskString; 172 } 173 174 180 public void setMask(String mask) 181 throws InvalidMaskException 182 { 183 184 Perl5Compiler patternCompiler = new Perl5Compiler(); 185 186 maskString = mask; 187 188 int maskOptions = Perl5Compiler.DEFAULT_MASK; 190 191 try 192 { 193 log.debug("Compiling pattern " + maskString); 194 maskPattern = patternCompiler.compile(maskString, maskOptions); 195 } 196 catch (MalformedPatternException mpe) 197 { 198 throw new InvalidMaskException("Could not compile pattern " + maskString, mpe); 199 } 200 } 201 202 207 public String getMaskMessage() 208 { 209 return maskMessage; 210 } 211 212 217 public void setMaskMessage(String message) 218 { 219 this.maskMessage = message; 220 } 221 } 222 | Popular Tags |