View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.transport.tcp;
8   
9   import org.mule.api.endpoint.ImmutableEndpoint;
10  
11  import java.net.InetAddress;
12  import java.net.InetSocketAddress;
13  
14  /**
15   * This is used to adapt an endpoint so that it can be used as a key for sockets.  It must
16   * meet two requirements: (1) implement hash and equals in a way that reflects socket identity
17   * (ie using address and port); (2) allow access to the endpoint for use in the socket factory.
18   * For simplicity we also expose the connector, address and port directly.
19   */
20  public class TcpSocketKey
21  {
22  
23      private InetSocketAddress address;
24      private ImmutableEndpoint endpoint;
25  
26      public TcpSocketKey(ImmutableEndpoint endpoint)
27      {
28          if (!(endpoint.getConnector() instanceof TcpConnector))
29          {
30              throw new IllegalArgumentException("Sockets must be keyed via a TCP endpoint");
31          }
32          this.endpoint = endpoint;
33          address = new InetSocketAddress(
34                  endpoint.getEndpointURI().getHost(),
35                  endpoint.getEndpointURI().getPort());
36      }
37  
38      @Override
39      public boolean equals(Object obj)
40      {
41          return obj instanceof TcpSocketKey && address.equals(((TcpSocketKey) obj).address);
42      }
43  
44      @Override
45      public int hashCode()
46      {
47          return address.hashCode();
48      }
49  
50      public ImmutableEndpoint getEndpoint()
51      {
52          return endpoint;
53      }
54  
55      public TcpConnector getConnector()
56      {
57          return (TcpConnector) endpoint.getConnector();
58      }
59  
60      public InetAddress getInetAddress()
61      {
62          return address.getAddress();
63      }
64  
65      public int getPort()
66      {
67          return address.getPort();
68      }
69  
70      @Override
71      public String toString()
72      {
73          return getInetAddress() + ":" + getPort();
74      }
75  
76  }