1 /**
2 * Copyright 2011 The Apache Software Foundation
3 *
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 */
20 package org.apache.hadoop.hbase.util;
21
22 import java.net.InetSocketAddress;
23
24 /**
25 * Utility for network addresses, resolving and naming.
26 */
27 public class Addressing {
28 public static final String VALID_PORT_REGEX = "[\\d]+";
29 public static final String HOSTNAME_PORT_SEPARATOR = ":";
30
31 /**
32 * @param hostAndPort Formatted as <code><hostname> ':' <port></code>
33 * @return An InetSocketInstance
34 */
35 public static InetSocketAddress createInetSocketAddressFromHostAndPortStr(
36 final String hostAndPort) {
37 return new InetSocketAddress(parseHostname(hostAndPort), parsePort(hostAndPort));
38 }
39
40 /**
41 * @param hostname Server hostname
42 * @param port Server port
43 * @return Returns a concatenation of <code>hostname</code> and
44 * <code>port</code> in following
45 * form: <code><hostname> ':' <port></code>. For example, if hostname
46 * is <code>example.org</code> and port is 1234, this method will return
47 * <code>example.org:1234</code>
48 */
49 public static String createHostAndPortStr(final String hostname, final int port) {
50 return hostname + HOSTNAME_PORT_SEPARATOR + port;
51 }
52
53 /**
54 * @param hostAndPort Formatted as <code><hostname> ':' <port></code>
55 * @return The hostname portion of <code>hostAndPort</code>
56 */
57 public static String parseHostname(final String hostAndPort) {
58 int colonIndex = hostAndPort.lastIndexOf(HOSTNAME_PORT_SEPARATOR);
59 if (colonIndex < 0) {
60 throw new IllegalArgumentException("Not a host:port pair: " + hostAndPort);
61 }
62 return hostAndPort.substring(0, colonIndex);
63 }
64
65 /**
66 * @param hostAndPort Formatted as <code><hostname> ':' <port></code>
67 * @return The port portion of <code>hostAndPort</code>
68 */
69 public static int parsePort(final String hostAndPort) {
70 int colonIndex = hostAndPort.lastIndexOf(HOSTNAME_PORT_SEPARATOR);
71 if (colonIndex < 0) {
72 throw new IllegalArgumentException("Not a host:port pair: " + hostAndPort);
73 }
74 return Integer.parseInt(hostAndPort.substring(colonIndex + 1));
75 }
76 }