1 | |
|
2 | |
|
3 | |
|
4 | |
|
5 | |
|
6 | |
|
7 | |
|
8 | |
|
9 | |
|
10 | |
|
11 | |
|
12 | |
|
13 | |
|
14 | |
|
15 | |
|
16 | |
|
17 | |
package org.apache.commons.latka.validators; |
18 | |
|
19 | |
import org.apache.commons.latka.Validator; |
20 | |
import org.apache.commons.latka.ValidationException; |
21 | |
|
22 | |
import org.apache.commons.latka.http.Response; |
23 | |
|
24 | |
import java.text.MessageFormat; |
25 | |
|
26 | |
|
27 | |
|
28 | |
|
29 | |
|
30 | |
|
31 | |
|
32 | |
public class ByteLengthValidator extends BaseValidator implements Validator { |
33 | |
|
34 | |
|
35 | |
|
36 | 0 | protected int _minLength = 0; |
37 | 0 | protected int _maxLength = -1; |
38 | |
|
39 | 0 | protected static final MessageFormat MAX_MESSAGE = new MessageFormat("Expected at most {0,number,integer} bytes. Found {1,number,integer}."); |
40 | 0 | protected static final MessageFormat MIN_MESSAGE = new MessageFormat("Expected at least {0,number,integer} bytes. Found {1,number,integer}."); |
41 | |
|
42 | |
|
43 | |
|
44 | |
public ByteLengthValidator() { |
45 | 0 | this(null,0,-1); |
46 | 0 | } |
47 | |
|
48 | |
public ByteLengthValidator(String label) { |
49 | 0 | this(label,0,-1); |
50 | 0 | } |
51 | |
|
52 | |
public ByteLengthValidator(int min, int max) { |
53 | 0 | this(null,min,max); |
54 | 0 | } |
55 | |
|
56 | |
public ByteLengthValidator(String label, int min, int max) { |
57 | 0 | super(label); |
58 | 0 | _minLength = min; |
59 | 0 | _maxLength = max; |
60 | 0 | } |
61 | |
|
62 | |
|
63 | |
|
64 | |
public void setMinLength(int length) { |
65 | 0 | _minLength = length; |
66 | 0 | } |
67 | |
|
68 | |
public void setMaxLength(int length) { |
69 | 0 | _maxLength = length; |
70 | 0 | } |
71 | |
|
72 | |
public void validate(Response response) |
73 | |
throws ValidationException { |
74 | |
|
75 | 0 | int byteLength = response.getByteLength(); |
76 | |
|
77 | 0 | if (_maxLength > -1) { |
78 | 0 | if (byteLength > _maxLength) { |
79 | 0 | fail(MAX_MESSAGE.format(new Object[] { new Integer(_maxLength), new Integer(byteLength) }).toString()); |
80 | |
} |
81 | |
} |
82 | |
|
83 | 0 | if (byteLength < _minLength) { |
84 | 0 | fail(MIN_MESSAGE.format(new Object[] { new Integer(_minLength), new Integer(byteLength) }).toString()); |
85 | |
} |
86 | 0 | } |
87 | |
|
88 | |
} |