View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.net;
19  
20  import static org.junit.Assert.assertEquals;
21  import org.apache.commons.lang.StringUtils;
22  import org.apache.hadoop.hbase.testclassification.MiscTests;
23  import org.apache.hadoop.hbase.testclassification.SmallTests;
24  import org.junit.Test;
25  import org.junit.experimental.categories.Category;
26  
27  @Category({ MiscTests.class, SmallTests.class })
28  public class TestAddress {
29  
30    @Test
31    public void testGetHostWithoutDomain() {
32      assertEquals("a:123",
33          toStringWithoutDomain(Address.fromParts("a.b.c", 123)));
34      assertEquals("1:123",
35          toStringWithoutDomain(Address.fromParts("1.b.c", 123)));
36      assertEquals("123.456.789.1:123",
37          toStringWithoutDomain(Address.fromParts("123.456.789.1", 123)));
38      assertEquals("[2001:db8::1]:80",
39          toStringWithoutDomain(Address.fromParts("[2001:db8::1]", 80)));
40    }
41  
42    private String toStringWithoutDomain(Address address) {
43      String hostname = address.getHostname();
44      String[] parts = hostname.split("\\.");
45      if (parts.length > 1) {
46        for (String part: parts) {
47          if (!StringUtils.isNumeric(part)) {
48            return Address.fromParts(parts[0], address.getPort()).toString();
49          }
50        }
51      }
52      return address.toString();
53    }
54  }