KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > net > util > InetSocketAddressList


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.net.util;
5
6 import com.tc.util.Assert;
7 import com.tc.util.StringUtil;
8
9 import java.net.InetSocketAddress JavaDoc;
10 import java.text.ParseException JavaDoc;
11 import java.util.ArrayList JavaDoc;
12 import java.util.List JavaDoc;
13 import java.util.regex.Matcher JavaDoc;
14 import java.util.regex.Pattern JavaDoc;
15
16 public final class InetSocketAddressList {
17
18   private static final Pattern JavaDoc ADDRESS_PATTERN = Pattern.compile("^([^:]+):(\\p{Digit}+)$");
19
20   private final InetSocketAddress JavaDoc[] addressList;
21
22   public InetSocketAddressList(InetSocketAddress JavaDoc[] addressList) {
23     Assert.assertNoNullElements(addressList);
24     this.addressList = addressList;
25   }
26
27   public InetSocketAddress JavaDoc[] addresses() {
28     return addressList;
29   }
30
31   public String JavaDoc toString() {
32     String JavaDoc[] addresses = new String JavaDoc[addressList.length];
33     for (int pos = 0; pos < addressList.length; pos++) {
34       addresses[pos] = addressList[pos].getHostName() + ":" + addressList[pos].getPort();
35     }
36     return StringUtil.toString(addresses, ",", null, null);
37   }
38
39   public static InetSocketAddress JavaDoc[] parseAddresses(String JavaDoc list) throws ParseException JavaDoc {
40     Assert.assertNotNull(list);
41     List JavaDoc addressList = new ArrayList JavaDoc();
42     String JavaDoc[] addresses = list.split(",");
43     int currentPosition = 0;
44     for (int pos = 0; pos < addresses.length; ++pos) {
45       Matcher JavaDoc addressMatcher = ADDRESS_PATTERN.matcher(addresses[pos]);
46       if (!addressMatcher.matches()) {
47         throw new ParseException JavaDoc("Unable to parse address, expected a format of <host>:<port>", currentPosition);
48       } else {
49         addressList.add(new InetSocketAddress JavaDoc(addressMatcher.group(1), Integer.parseInt(addressMatcher.group(2))));
50       }
51       // Account for the comma separator
52
if (pos > 0) ++currentPosition;
53       currentPosition += addresses[pos].length();
54     }
55     InetSocketAddress JavaDoc[] rv = new InetSocketAddress JavaDoc[addressList.size()];
56     addressList.toArray(rv);
57     return rv;
58   }
59
60 }
61
Popular Tags