/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package org.jboss.netty.channel.socket;

import static org.junit.Assert.*;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.jboss.netty.bootstrap.ConnectionlessBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.util.TestUtil;
import org.jboss.netty.util.internal.ExecutorUtil;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

public abstract class AbstractDatagramMulticastTest {


    private static ExecutorService executor;


    @BeforeClass
    public static void init() {
        executor = Executors.newCachedThreadPool();
    }

    @AfterClass
    public static void destroy() {
        ExecutorUtil.terminate(executor);
    }

    protected abstract DatagramChannelFactory newServerSocketChannelFactory(Executor executor);
    protected abstract DatagramChannelFactory newClientSocketChannelFactory(Executor executor);

    @Test
    public void testMulticast() throws Throwable {
        ConnectionlessBootstrap sb = new ConnectionlessBootstrap(newServerSocketChannelFactory(executor));
        ConnectionlessBootstrap cb = new ConnectionlessBootstrap(newClientSocketChannelFactory(executor));
        MulticastTestHandler mhandler = new MulticastTestHandler();

        cb.getPipeline().addFirst("handler", mhandler);
        sb.getPipeline().addFirst("handler", new SimpleChannelUpstreamHandler());

        int port = TestUtil.getFreePort();

        NetworkInterface iface = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());

        // check if the NetworkInterface is null, this is the case on my ubuntu dev machine but not on osx and windows.
        // if so fail back the the first interface
        if (iface == null) {
            // use nextElement() as NetWorkInterface.getByIndex(0) returns null
            iface = NetworkInterface.getNetworkInterfaces().nextElement();
        }
        sb.setOption("networkInterface", iface);
        sb.setOption("reuseAddress", true);

        Channel sc = sb.bind(new InetSocketAddress(port));


        String group = "230.0.0.1";
        InetSocketAddress groupAddress = new InetSocketAddress(group, port);

        cb.setOption("networkInterface", iface);
        cb.setOption("reuseAddress", true);

        DatagramChannel cc = (DatagramChannel) cb.bind(new InetSocketAddress(port));

        assertTrue(cc.joinGroup(groupAddress, iface).awaitUninterruptibly().isSuccess());

        assertTrue(sc.write(wrapInt(1), groupAddress).awaitUninterruptibly().isSuccess());


        assertTrue(mhandler.await());

        assertTrue(sc.write(wrapInt(1), groupAddress).awaitUninterruptibly().isSuccess());


        // leave the group
        assertTrue(cc.leaveGroup(groupAddress, iface).awaitUninterruptibly().isSuccess());

        // sleep a second to make sure we left the group
        Thread.sleep(1000);

        // we should not receive a message anymore as we left the group before
        assertTrue(sc.write(wrapInt(1), groupAddress).awaitUninterruptibly().isSuccess());

        sc.close().awaitUninterruptibly();
        cc.close().awaitUninterruptibly();

    }

    private static ChannelBuffer wrapInt(int value) {
        ChannelBuffer buf = ChannelBuffers.buffer(4);
        buf.writeInt(value);
        return buf;
    }

    private final class MulticastTestHandler extends SimpleChannelUpstreamHandler {
        private final CountDownLatch latch = new CountDownLatch(1);

        private boolean done = false;
        private volatile boolean fail = false;

        @Override
        public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
            super.messageReceived(ctx, e);
            if (done) {
                fail = true;
            }

            Assert.assertEquals(1,((ChannelBuffer)e.getMessage()).readInt());

            latch.countDown();

            // mark the handler as done as we only are supposed to receive one message
            done = true;
        }

        public boolean await() throws Exception {
            boolean success = latch.await(10, TimeUnit.SECONDS);
            if (fail) {
                // fail if we receive an message after we are done
                Assert.fail();
            }
            return success;
        }

    }
}

@@ -704,16 +704,46 @@
 ert.*;%0A%0A
+import java.net.Inet4Address;%0A
 import j
@@ -828,24 +828,54 @@
 kInterface;%0A
+import java.util.Enumeration;%0A
 import java.
@@ -2681,272 +2681,338 @@
 e = 
-NetworkInterface.getByInetAddress(InetAddress.getLocalHost());%0A%0A        // check if the NetworkInterface is null, this is the case on my ubuntu dev machine but not on osx and windows.%0A        // if so fail back the the first interface%0A        if (iface == null
+null;%0A        Enumeration%3CNetworkInterface%3E interfaces = NetworkInterface.getNetworkInterfaces();%0A        while (interfaces.hasMoreElements()) %7B%0A            NetworkInterface inf = interfaces.nextElement();%0A            %0A            // Only try to use interface if its not a loopback interface%0A            if (!inf.isLoopback()
 ) %7B%0A
+%0A
     
@@ -3023,160 +3023,387 @@
     
-// use nextElement() as NetWorkInterface.getByIndex(0) returns null%0A            iface = NetworkInterface.getNetworkInterfaces().nextElement();%0A        %7D
+    Enumeration%3CInetAddress%3E addresses = inf.getInetAddresses();%0A                while (addresses.hasMoreElements()) %7B%0A                    InetAddress addr = addresses.nextElement();%0A                    if (addr instanceof Inet4Address) %7B%0A                        iface = inf;%0A                        break;%0A                    %7D%0A                %7D%0A            %7D%0A        %7D%0A        
 %0A   

Make sure multicast test use correct interface. This also fix #373