1 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 ; 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.compile("^([^:]+):(\\p{Digit}+)$"); 19 20 private final InetSocketAddress [] addressList; 21 22 public InetSocketAddressList(InetSocketAddress [] addressList) { 23 Assert.assertNoNullElements(addressList); 24 this.addressList = addressList; 25 } 26 27 public InetSocketAddress [] addresses() { 28 return addressList; 29 } 30 31 public String toString() { 32 String [] addresses = new String [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 [] parseAddresses(String list) throws ParseException { 40 Assert.assertNotNull(list); 41 List addressList = new ArrayList (); 42 String [] addresses = list.split(","); 43 int currentPosition = 0; 44 for (int pos = 0; pos < addresses.length; ++pos) { 45 Matcher addressMatcher = ADDRESS_PATTERN.matcher(addresses[pos]); 46 if (!addressMatcher.matches()) { 47 throw new ParseException ("Unable to parse address, expected a format of <host>:<port>", currentPosition); 48 } else { 49 addressList.add(new InetSocketAddress (addressMatcher.group(1), Integer.parseInt(addressMatcher.group(2)))); 50 } 51 if (pos > 0) ++currentPosition; 53 currentPosition += addresses[pos].length(); 54 } 55 InetSocketAddress [] rv = new InetSocketAddress [addressList.size()]; 56 addressList.toArray(rv); 57 return rv; 58 } 59 60 } 61 | Popular Tags |