01: /*
02: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
03: */
04: package com.tc.net.util;
05:
06: import com.tc.util.Assert;
07: import com.tc.util.StringUtil;
08:
09: import java.net.InetSocketAddress;
10: import java.text.ParseException;
11: import java.util.ArrayList;
12: import java.util.List;
13: import java.util.regex.Matcher;
14: import java.util.regex.Pattern;
15:
16: public final class InetSocketAddressList {
17:
18: private static final Pattern ADDRESS_PATTERN = Pattern
19: .compile("^([^:]+):(\\p{Digit}+)$");
20:
21: private final InetSocketAddress[] addressList;
22:
23: public InetSocketAddressList(InetSocketAddress[] addressList) {
24: Assert.assertNoNullElements(addressList);
25: this .addressList = addressList;
26: }
27:
28: public InetSocketAddress[] addresses() {
29: return addressList;
30: }
31:
32: public String toString() {
33: String[] addresses = new String[addressList.length];
34: for (int pos = 0; pos < addressList.length; pos++) {
35: addresses[pos] = addressList[pos].getHostName() + ":"
36: + addressList[pos].getPort();
37: }
38: return StringUtil.toString(addresses, ",", null, null);
39: }
40:
41: public static InetSocketAddress[] parseAddresses(String list)
42: throws ParseException {
43: Assert.assertNotNull(list);
44: List addressList = new ArrayList();
45: String[] addresses = list.split(",");
46: int currentPosition = 0;
47: for (int pos = 0; pos < addresses.length; ++pos) {
48: Matcher addressMatcher = ADDRESS_PATTERN
49: .matcher(addresses[pos]);
50: if (!addressMatcher.matches()) {
51: throw new ParseException(
52: "Unable to parse address, expected a format of <host>:<port>",
53: currentPosition);
54: } else {
55: addressList.add(new InetSocketAddress(addressMatcher
56: .group(1), Integer.parseInt(addressMatcher
57: .group(2))));
58: }
59: // Account for the comma separator
60: if (pos > 0)
61: ++currentPosition;
62: currentPosition += addresses[pos].length();
63: }
64: InetSocketAddress[] rv = new InetSocketAddress[addressList
65: .size()];
66: addressList.toArray(rv);
67: return rv;
68: }
69:
70: }
|