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