Split a freeform string into a host and port, without strict validation. Note that the host-only formats will leave the port field undefined. You can use #withDefaultPort(int) to patch in a default value. @param hostPortString the input string to parse. @return if parsing was successful, a
(String hostPortString)
| 177 | |
| 178 | |
| 179 | public static HostAndPort fromString(String hostPortString) { |
| 180 | checkNotNull(hostPortString); |
| 181 | String host; |
| 182 | String portString = null; |
| 183 | boolean hasBracketlessColons = false; |
| 184 | if (hostPortString.startsWith("[")) { |
| 185 | String[] hostAndPort = getHostAndPortFromBracketedHost(hostPortString); |
| 186 | host = hostAndPort[0]; |
| 187 | portString = hostAndPort[1]; |
| 188 | } else { |
| 189 | int colonPos = hostPortString.indexOf(':'); |
| 190 | if (colonPos >= 0 && hostPortString.indexOf(':', colonPos + 1) == -1) { |
| 191 | // Exactly 1 colon. Split into host:port. |
| 192 | host = hostPortString.substring(0, colonPos); |
| 193 | portString = hostPortString.substring(colonPos + 1); |
| 194 | } else { |
| 195 | // 0 or 2+ colons. Bare hostname or IPv6 literal. |
| 196 | host = hostPortString; |
| 197 | hasBracketlessColons = (colonPos >= 0); |
| 198 | } |
| 199 | } |
| 200 | int port = NO_PORT; |
| 201 | if (!Strings.isNullOrEmpty(portString)) { |
| 202 | // Try to parse the whole port string as a number. |
| 203 | // JDK7 accepts leading plus signs. We don't want to. |
| 204 | checkArgument(!portString.startsWith("+"), "Unparseable port number: %s", hostPortString); |
| 205 | try { |
| 206 | port = Integer.parseInt(portString); |
| 207 | } catch (NumberFormatException e) { |
| 208 | throw new IllegalArgumentException("Unparseable port number: " + hostPortString); |
| 209 | } |
| 210 | checkArgument(isValidPort(port), "Port number out of range: %s", hostPortString); |
| 211 | } |
| 212 | return new HostAndPort(host, port, hasBracketlessColons); |
| 213 | } |
| 214 | |
| 215 | /** |
| 216 | * Parses a bracketed host-port string, throwing IllegalArgumentException if parsing fails. |
no test coverage detected