1 16 17 package org.apache.cocoon.components.elementprocessor.types; 18 19 import org.apache.cocoon.CascadingIOException; 20 21 import java.io.IOException ; 22 23 30 public class NumericConverter 31 { 32 private static final Validator _non_negative_validator = new Validator() 33 { 34 public IOException validate(final Number number) { 35 IOException e = null; 36 37 if (number.intValue() < 0) { 38 e = new IOException("\"" + number.intValue() 39 + "\" is not a non-negative integer"); 40 } 41 return e; 42 } 43 }; 44 private static final Validator _positive_validator = new Validator() 45 { 46 public IOException validate(final Number number) { 47 IOException e = null; 48 49 if (number.intValue() < 1) { 50 e = new IOException("\"" + number.intValue() 51 + "\" is not a positive integer"); 52 } 53 return e; 54 } 55 }; 56 57 private NumericConverter() { 58 } 59 60 68 69 public static NumericResult extractDouble(final String value) { 70 return extractDouble(value, null); 71 } 72 73 84 85 public static NumericResult extractDouble(final String value, 86 final Validator validator) { 87 String input = (value == null) ? "" : value.trim(); 88 NumericResult result = null; 89 90 try { 91 Number number = new Double (input); 92 IOException exception = null; 93 94 if (validator != null) { 95 exception = validator.validate(number); 96 } 97 if (exception == null) { 98 result = new NumericResult(number); 99 } else { 100 result = new NumericResult(exception); 101 } 102 } catch (NumberFormatException ignored) { 103 result = new NumericResult( 104 new CascadingIOException( 105 "\"" + input + "\" does not represent a double value", ignored)); 106 } 107 return result; 108 } 109 110 118 119 public static NumericResult extractInteger(final String value) { 120 return extractInteger(value, null); 121 } 122 123 134 135 public static NumericResult extractInteger(final String value, 136 final Validator validator) { 137 String input = (value == null) ? "" : value.trim(); 138 NumericResult result = null; 139 140 try { 141 Number number = new Integer (input); 142 IOException exception = null; 143 144 if (validator != null) { 145 exception = validator.validate(number); 146 } 147 if (exception == null) { 148 result = new NumericResult(number); 149 } else { 150 result = new NumericResult(exception); 151 } 152 } catch (NumberFormatException ignored) { 153 result = new NumericResult( 154 new CascadingIOException( 155 "\"" + input + "\" does not represent an integer value", ignored)); 156 } 157 return result; 158 } 159 160 170 171 public static NumericResult extractPositiveInteger(final String value) { 172 return extractInteger(value, _positive_validator); 173 } 174 175 185 186 public static NumericResult extractNonNegativeInteger(final String value) { 187 return extractInteger(value, _non_negative_validator); 188 } 189 } | Popular Tags |