Parses a TTL-like value, which can either be expressed as a number or a BIND-style string with numbers and units. @param s The string representing the numeric value. @param clamp Whether to clamp values in the range [MAX_VALUE + 1, 2^32 -1] to MAX_VALUE. This should be donw for TTLs, but not other
(String s, boolean clamp)
| 34 | * @throws NumberFormatException The string was not in a valid TTL format. |
| 35 | */ |
| 36 | public static long |
| 37 | parse(String s, boolean clamp) { |
| 38 | if (s == null || s.length() == 0 || !Character.isDigit(s.charAt(0))) |
| 39 | throw new NumberFormatException(); |
| 40 | long value = 0; |
| 41 | long ttl = 0; |
| 42 | for (int i = 0; i < s.length(); i++) { |
| 43 | char c = s.charAt(i); |
| 44 | long oldvalue = value; |
| 45 | if (Character.isDigit(c)) { |
| 46 | value = (value * 10) + Character.getNumericValue(c); |
| 47 | if (value < oldvalue) |
| 48 | throw new NumberFormatException(); |
| 49 | } else { |
| 50 | switch (Character.toUpperCase(c)) { |
| 51 | case 'W': value *= 7; |
| 52 | case 'D': value *= 24; |
| 53 | case 'H': value *= 60; |
| 54 | case 'M': value *= 60; |
| 55 | case 'S': break; |
| 56 | default: throw new NumberFormatException(); |
| 57 | } |
| 58 | ttl += value; |
| 59 | value = 0; |
| 60 | if (ttl > 0xFFFFFFFFL) |
| 61 | throw new NumberFormatException(); |
| 62 | } |
| 63 | } |
| 64 | if (ttl == 0) |
| 65 | ttl = value; |
| 66 | |
| 67 | if (ttl > 0xFFFFFFFFL) |
| 68 | throw new NumberFormatException(); |
| 69 | else if (ttl > MAX_VALUE && clamp) |
| 70 | ttl = MAX_VALUE; |
| 71 | return ttl; |
| 72 | } |
| 73 | |
| 74 | /** |
| 75 | * Parses a TTL, which can either be expressed as a number or a BIND-style |
no test coverage detected