1 19 20 package com.sslexplorer.input.validators; 21 22 import java.util.Properties ; 23 import java.util.regex.Matcher ; 24 import java.util.regex.Pattern ; 25 26 import org.apache.commons.logging.Log; 27 import org.apache.commons.logging.LogFactory; 28 29 import com.sslexplorer.boot.CodedException; 30 import com.sslexplorer.boot.PropertyDefinition; 31 import com.sslexplorer.boot.PropertyValidator; 32 import com.sslexplorer.boot.ReplacementEngine; 33 import com.sslexplorer.boot.Replacer; 34 import com.sslexplorer.core.CoreException; 35 import com.sslexplorer.core.stringreplacement.VariableReplacement; 36 37 38 47 public class IntegerValidator implements PropertyValidator { 48 49 final static Log log = LogFactory.getLog(IntegerValidator.class); 50 51 private int defaultMin = 0; 52 private int defaultMax = Integer.MAX_VALUE; 53 54 60 public IntegerValidator(int defaultMin, int defaultMax) { 61 this.defaultMin = defaultMin; 62 this.defaultMax = defaultMax; 63 } 64 65 70 public IntegerValidator() { 71 } 72 73 76 public void validate(PropertyDefinition definition, String value, Properties properties) throws CodedException { 77 78 int min = defaultMin; 80 try { 81 if(properties != null && properties.containsKey("minValue")) 82 min = Integer.parseInt(properties.getProperty("minValue")); 83 } 84 catch(NumberFormatException nfe) { 85 log.error("Failed to get minimum value for validator.", nfe); 86 throw new CoreException(ErrorConstants.ERR_INTERNAL_ERROR, ErrorConstants.CATEGORY_NAME, ErrorConstants.BUNDLE_NAME, null, value); 87 } 88 int max = defaultMax; 89 try { 90 if(properties != null && properties.containsKey("maxValue")) 91 max = Integer.parseInt(properties.getProperty("maxValue")); 92 } 93 catch(NumberFormatException nfe) { 94 log.error("Failed to get maximum value for validator.", nfe); 95 throw new CoreException(ErrorConstants.ERR_INTERNAL_ERROR, ErrorConstants.CATEGORY_NAME, ErrorConstants.BUNDLE_NAME, null, value); 96 } 97 98 101 if(properties != null && "true".equalsIgnoreCase(properties.getProperty("replacementVariables"))) { 102 Replacer r = new Replacer() { 103 public String getReplacement(Pattern pattern, Matcher matcher, String replacementPattern) { 104 return replacementPattern; 105 } 106 }; 107 ReplacementEngine re = new ReplacementEngine(); 108 re.addPattern(VariableReplacement.VARIABLE_PATTERN, r, String.valueOf(min)); 109 value = re.replace(value); 110 } 111 112 try { 114 int i = Integer.parseInt(value); 115 if(i < min || i > max) { 116 throw new CoreException(ErrorConstants.ERR_INTEGER_OUT_OF_RANGE, ErrorConstants.CATEGORY_NAME, ErrorConstants.BUNDLE_NAME, null, String.valueOf(min), String.valueOf(max), value, null); 117 } 118 } 119 catch(NumberFormatException nfe) { 120 throw new CoreException(ErrorConstants.ERR_NOT_AN_INTEGER, ErrorConstants.CATEGORY_NAME, ErrorConstants.BUNDLE_NAME, null, String.valueOf(min), String.valueOf(max), value, null); 121 } 122 } 123 124 } 125 | Popular Tags |