View Javadoc

1   /*
2    * $Id: MulticastMessageReceiver.java 7963 2007-08-21 08:53:15Z dirk.olmes $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSource, Inc.  All rights reserved.  http://www.mulesource.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.providers.multicast;
12  
13  import org.mule.providers.AbstractConnector;
14  import org.mule.providers.udp.UdpMessageReceiver;
15  import org.mule.umo.UMOComponent;
16  import org.mule.umo.endpoint.UMOEndpoint;
17  import org.mule.umo.lifecycle.InitialisationException;
18  
19  import java.io.IOException;
20  import java.net.DatagramPacket;
21  import java.net.DatagramSocket;
22  import java.net.InetAddress;
23  import java.net.MulticastSocket;
24  import java.net.URI;
25  
26  import javax.resource.spi.work.Work;
27  
28  /**
29   * <code>MulticastMessageReceiver</code> TODO (document class)
30   */
31  public class MulticastMessageReceiver extends UdpMessageReceiver
32  {
33  
34      public MulticastMessageReceiver(AbstractConnector connector, UMOComponent component, UMOEndpoint endpoint)
35          throws InitialisationException
36      {
37          super(connector, component, endpoint);
38      }
39  
40      protected DatagramSocket createSocket(URI uri, InetAddress inetAddress) throws IOException
41      {
42          MulticastSocket socket = new MulticastSocket(uri.getPort());
43          socket.joinGroup(inetAddress);
44          return socket;
45      }
46  
47      protected Work createWork(DatagramPacket packet) throws IOException
48      {
49          return new MulticastWorker(packet);
50      }
51  
52      public class MulticastWorker extends UdpWorker
53      {
54          public MulticastWorker(DatagramPacket packet)
55          {
56              super(socket, packet);
57          }
58  
59          public void dispose()
60          {
61              // Do not close socket as we reuse it
62              // So do not call super.doDispose();
63          }
64      }
65  
66      protected void doDispose()
67      {
68          if (socket != null && !socket.isClosed())
69          {
70              try
71              {
72                  ((MulticastSocket)socket).leaveGroup(inetAddress);
73              }
74              catch (IOException e)
75              {
76                  logger.error("failed to leave group: " + e.getMessage(), e);
77              }
78          }
79          super.doDispose();
80      }
81  
82  }