View Javadoc
1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.channel.local;
17  
18  import static io.netty.util.internal.ObjectUtil.checkNonEmptyAfterTrim;
19  
20  import io.netty.channel.Channel;
21  
22  import java.net.SocketAddress;
23  
24  /**
25   * An endpoint in the local transport.  Each endpoint is identified by a unique
26   * case-insensitive string.
27   */
28  public final class LocalAddress extends SocketAddress implements Comparable<LocalAddress> {
29  
30      private static final long serialVersionUID = 4644331421130916435L;
31  
32      public static final LocalAddress ANY = new LocalAddress("ANY");
33  
34      private final String id;
35      private final String strVal;
36  
37      /**
38       * Creates a new ephemeral port based on the ID of the specified channel.
39       * Note that we prepend an upper-case character so that it never conflicts with
40       * the addresses created by a user, which are always lower-cased on construction time.
41       */
42      LocalAddress(Channel channel) {
43          StringBuilder buf = new StringBuilder(16);
44          buf.append("local:E");
45          buf.append(Long.toHexString(channel.hashCode() & 0xFFFFFFFFL | 0x100000000L));
46          buf.setCharAt(7, ':');
47          id = buf.substring(6);
48          strVal = buf.toString();
49      }
50  
51      /**
52       * Creates a new instance with the specified ID.
53       */
54      public LocalAddress(String id) {
55          this.id = checkNonEmptyAfterTrim(id, "id").toLowerCase();
56          this.strVal = "local:" + this.id;
57      }
58  
59      /**
60       * Returns the ID of this address.
61       */
62      public String id() {
63          return id;
64      }
65  
66      @Override
67      public int hashCode() {
68          return id.hashCode();
69      }
70  
71      @Override
72      public boolean equals(Object o) {
73          if (!(o instanceof LocalAddress)) {
74              return false;
75          }
76  
77          return id.equals(((LocalAddress) o).id);
78      }
79  
80      @Override
81      public int compareTo(LocalAddress o) {
82          return id.compareTo(o.id);
83      }
84  
85      @Override
86      public String toString() {
87          return strVal;
88      }
89  }