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.multicast;
8   
9   import org.mule.api.endpoint.ImmutableEndpoint;
10  import org.mule.api.transport.Connector;
11  import org.mule.transport.udp.UdpSocketFactory;
12  
13  import java.io.IOException;
14  import java.net.DatagramSocket;
15  import java.net.InetAddress;
16  import java.net.MulticastSocket;
17  
18  /**
19   * TODO
20   */
21  public class MulticastSocketFactory extends UdpSocketFactory
22  {
23  
24      public Object makeObject(Object key) throws Exception
25      {
26          ImmutableEndpoint ep = (ImmutableEndpoint)key;
27          MulticastSocket socket = (MulticastSocket)super.makeObject(key);
28          socket.setLoopbackMode(((MulticastConnector)ep.getConnector()).isLoopback());
29          int ttl  = ((MulticastConnector)ep.getConnector()).getTimeToLive();
30          if(ttl!= Connector.INT_VALUE_NOT_SET)
31          {
32              socket.setTimeToLive(ttl);
33          }
34          return socket;
35      }
36  
37  
38      @java.lang.Override
39      public void destroyObject(Object key, Object object) throws Exception
40      {
41          ImmutableEndpoint ep = (ImmutableEndpoint)key;
42          InetAddress inetAddress;
43          String host = ep.getEndpointURI().getHost();
44          if("null".equalsIgnoreCase(host))
45          {
46              inetAddress = InetAddress.getLocalHost();
47          }
48          else
49          {
50              inetAddress = InetAddress.getByName(host);
51          }
52          MulticastSocket socket = (MulticastSocket)object;
53          socket.leaveGroup(inetAddress);
54          super.destroyObject(key, object);
55      }
56  
57      protected DatagramSocket createSocket() throws IOException
58      {
59          return new MulticastSocket();
60      }
61  
62      protected DatagramSocket createSocket(int port) throws IOException
63      {
64          throw new IllegalArgumentException("A group host or IP address is required");
65      }
66  
67      protected DatagramSocket createSocket(int port, InetAddress inetAddress) throws IOException
68      {
69          MulticastSocket socket = new MulticastSocket(port);
70          socket.joinGroup(inetAddress);
71          return socket;
72      }
73  }