1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.xnap.util.prefs;
21
22 import java.util.StringTokenizer;
23
24 import org.xnap.XNap;
25 import org.xnap.util.PortRange;
26
27 /***
28 * A port range validator. Port ranges are used to specify on ore more tcp
29 * ports. The format is: [([:number:]*|[:number:]*-[:number:]*);]*
30 */
31 public class PortRangeValidator implements Validator
32 {
33
34
35
36 /***
37 * The default validator that allows ranges between
38 * {@link PortRange#MIN_PORT} and {@link PortRange#MAX_PORT}.
39 */
40 public static final PortRangeValidator DEFAULT = new PortRangeValidator();
41
42
43
44 private int min;
45 private int max;
46 private boolean valid;
47
48
49
50 public PortRangeValidator(int min, int max)
51 {
52 this.min = min;
53 this.max = max;
54 }
55
56 public PortRangeValidator()
57 {
58 this(PortRange.MIN_PORT, PortRange.MAX_PORT);
59 }
60
61
62
63 /***
64 * Checks if <code>value</code> is a valid port range string.
65 *
66 * @exception IllegalArgumentException if string format is invalid
67 */
68 public void validate(String value)
69 {
70 valid = false;
71
72 StringTokenizer t = new StringTokenizer(value, ";");
73 while (t.hasMoreTokens()) {
74 String ports = t.nextToken().trim();
75
76 if (ports.length() == 0) {
77 continue;
78 }
79
80 try {
81 if (ports.indexOf("-") != -1) {
82 StringTokenizer u = new StringTokenizer(ports, "-");
83 if (u.countTokens() == 2) {
84 int i = Integer.parseInt(u.nextToken());
85 int j = Integer.parseInt(u.nextToken());
86 check(i);
87 check(j);
88 valid |= (i <= j);
89 }
90 else {
91 throw(new IllegalArgumentException
92 (XNap.tr("Malformed range.")));
93 }
94 }
95 else {
96 check(Integer.parseInt(ports));
97 valid = true;
98 }
99 }
100 catch (NumberFormatException e) {
101 throw(new IllegalArgumentException
102 (XNap.tr("Malformed number.")));
103 }
104 }
105
106 if (!valid) {
107
108 throw new IllegalArgumentException(XNap.tr("No port given."));
109 }
110 }
111
112 /***
113 * Checks if <code>i</code> is in range.
114 *
115 * @exception IllegalArgumentException thrown if i is not in range
116 */
117 public void check(int i)
118 {
119 if (i < min || i > max) {
120 throw new IllegalArgumentException
121 (XNap.tr("Port out of range {0}.",
122 "(" + min + " - " + max + ")"));
123 }
124 }
125
126 }