01: package org.conform.validator;
02:
03: import org.conform.Validator;
04: import org.conform.ValidationException;
05:
06: import java.math.BigDecimal;
07: import java.math.BigInteger;
08:
09: public class PrecisionScaleValidator implements Validator {
10: int precision;
11: int scale = -1;
12:
13: public PrecisionScaleValidator(int precision) {
14: this .precision = precision;
15: }
16:
17: public PrecisionScaleValidator(int precision, int scale) {
18: this .precision = precision;
19: this .scale = scale;
20: }
21:
22: public Object validate(Object value) throws ValidationException {
23: if (value instanceof BigDecimal)
24: checkBigDecimal((BigDecimal) value);
25: else if (value instanceof BigInteger)
26: checkBigInteger((BigInteger) value);
27: return value;
28: }
29:
30: private void checkBigDecimal(BigDecimal bigDecimal)
31: throws ValidationException {
32: if (scale != -1 && bigDecimal.scale() > scale)
33: throw new ValidationException(
34: new ValidationException.Message(
35: "validation.numberScale", new Object[] {
36: bigDecimal, new Integer(scale) }));
37: if (bigDecimal.precision() > precision)
38: throw new ValidationException(
39: new ValidationException.Message(
40: "validation.numberPrecision",
41: new Object[] { bigDecimal,
42: new Integer(precision) }));
43: }
44:
45: private void checkBigInteger(BigInteger bigInteger)
46: throws ValidationException {
47: if (bigInteger.abs().toString().length() > precision)
48: throw new ValidationException(
49: new ValidationException.Message(
50: "validation.numberPrecision",
51: new Object[] { bigInteger,
52: new Integer(precision) }));
53: }
54: }
|