<commit_before>/*
 * JBoss, Home of Professional Open Source
 * Copyright 2008, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.jboss.xnio.nio.test;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import junit.framework.TestCase;
import static org.jboss.xnio.Buffers.flip;
import org.jboss.xnio.CloseableTcpAcceptor;
import org.jboss.xnio.CloseableTcpConnector;
import org.jboss.xnio.ConfigurableFactory;
import org.jboss.xnio.FutureConnection;
import org.jboss.xnio.IoFuture;
import org.jboss.xnio.IoHandler;
import org.jboss.xnio.IoHandlerFactory;
import org.jboss.xnio.IoUtils;
import static org.jboss.xnio.IoUtils.nullHandler;
import static org.jboss.xnio.IoUtils.safeClose;
import org.jboss.xnio.Xnio;
import org.jboss.xnio.channels.BoundChannel;
import org.jboss.xnio.channels.BoundServer;
import org.jboss.xnio.channels.CommonOptions;
import org.jboss.xnio.channels.ConnectedStreamChannel;
import org.jboss.xnio.channels.TcpChannel;
import org.jboss.xnio.log.Logger;
import org.jboss.xnio.nio.NioXnio;
import org.jboss.xnio.nio.NioXnioConfiguration;
import org.jboss.xnio.test.support.LoggingHelper;
import org.jboss.xnio.test.support.TestThreadFactory;

/**
 *
 */
public final class NioTcpTestCase extends TestCase {
    static {
        LoggingHelper.init();
    }

    private static final Logger log = Logger.getLogger("TEST");

    private final TestThreadFactory threadFactory = new TestThreadFactory();

    private static final int SERVER_PORT = 12345;

    private void doConnectionTest(final Runnable body, final IoHandler<? super TcpChannel> clientHandler, final IoHandler<? super TcpChannel> serverHandler) throws Exception {
        final NioXnioConfiguration conf = new NioXnioConfiguration();
        conf.setSelectorThreadFactory(threadFactory);
        conf.setExecutor(new ThreadPoolExecutor(4, 10, 1000L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(50)));
        Xnio xnio = NioXnio.create(conf);
        try {
            final ConfigurableFactory<BoundServer<SocketAddress,BoundChannel<SocketAddress>>> serverFactory = xnio.createTcpServer(new IoHandlerFactory<TcpChannel>() {
                public IoHandler<? super TcpChannel> createHandler() {
                    return new CatchingHandler<TcpChannel>(serverHandler, threadFactory);
                }
            }, new SocketAddress[] { new InetSocketAddress(Inet4Address.getByAddress(new byte[] { 127, 0, 0, 1 }), SERVER_PORT)});
            serverFactory.setOption(CommonOptions.REUSE_ADDRESSES, Boolean.TRUE);
            final BoundServer<SocketAddress, BoundChannel<SocketAddress>> server = serverFactory.create();
            try {
                final ConfigurableFactory<CloseableTcpConnector> connectorFactory = xnio.createTcpConnector();
                final CloseableTcpConnector connector = connectorFactory.create();
                try {
                    final IoFuture<TcpChannel> ioFuture = connector.connectTo(new InetSocketAddress(Inet4Address.getByAddress(new byte[] { 127, 0, 0, 1 }), SERVER_PORT), new CatchingHandler<TcpChannel>(clientHandler, threadFactory));
                    final TcpChannel channel = ioFuture.get();
                    try {
                        body.run();
                        channel.close();
                        connector.close();
                        server.close();
                        xnio.close();
                    } finally {
                        safeClose(channel);
                    }
                } finally {
                    IoUtils.safeClose(connector);
                }
            } finally {
                IoUtils.safeClose(server);
            }
        } finally {
            IoUtils.safeClose(xnio);
        }
    }

    public void testTcpConnect() throws Exception {
        threadFactory.clear();
        log.info("Test: testTcpConnect");
        doConnectionTest(new Runnable() {
            public void run() {
            }
        }, nullHandler(), nullHandler());
        threadFactory.await();
    }

    public void testClientTcpClose() throws Exception {
        threadFactory.clear();
        log.info("Test: testClientTcpClose");
        final CountDownLatch latch = new CountDownLatch(2);
        final AtomicBoolean clientOK = new AtomicBoolean(false);
        final AtomicBoolean serverOK = new AtomicBoolean(false);
        doConnectionTest(new Runnable() {
            public void run() {
                try {
                    assertTrue(latch.await(500L, TimeUnit.MILLISECONDS));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, new IoHandler<ConnectedStreamChannel<SocketAddress>>() {
            public void handleOpened(final ConnectedStreamChannel<SocketAddress> channel) {
                try {
                    channel.close();
                    clientOK.set(true);
                } catch (Throwable t) {
                    t.printStackTrace();
                    latch.countDown();
                    throw new RuntimeException(t);
                }
            }

            public void handleReadable(final ConnectedStreamChannel<SocketAddress> channel) {
            }

            public void handleWritable(final ConnectedStreamChannel<SocketAddress> channel) {
            }

            public void handleClosed(final ConnectedStreamChannel<SocketAddress> channel) {
                latch.countDown();
            }
        }, new IoHandler<ConnectedStreamChannel<SocketAddress>>() {
            public void handleOpened(final ConnectedStreamChannel<SocketAddress> channel) {
                try {
                    channel.resumeReads();
                } catch (Throwable t) {
                    t.printStackTrace();
                    try {
                        channel.close();
                    } catch (Throwable t2) {
                        t2.printStackTrace();
                        latch.countDown();
                        throw new RuntimeException(t);
                    }
                    throw new RuntimeException(t);
                }
            }

            public void handleReadable(final ConnectedStreamChannel<SocketAddress> channel) {
                try {
                    final int c = channel.read(ByteBuffer.allocate(100));
                    if (c == -1) {
                        serverOK.set(true);
                    }
                    channel.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            public void handleWritable(final ConnectedStreamChannel<SocketAddress> channel) {
            }

            public void handleClosed(final ConnectedStreamChannel<SocketAddress> channel) {
                latch.countDown();
            }
        });
        assertTrue(serverOK.get());
        assertTrue(clientOK.get());
        threadFactory.await();
    }

    public void testServerTcpClose() throws Exception {
        threadFactory.clear();
        log.info("Test: testServerTcpClose");
        final CountDownLatch latch = new CountDownLatch(2);
        final AtomicBoolean clientOK = new AtomicBoolean(false);<commit_msg>Better logging in test case<commit_after>/*
 * JBoss, Home of Professional Open Source
 * Copyright 2008, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.jboss.xnio.nio.test;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import junit.framework.TestCase;
import static org.jboss.xnio.Buffers.flip;
import org.jboss.xnio.CloseableTcpAcceptor;
import org.jboss.xnio.CloseableTcpConnector;
import org.jboss.xnio.ConfigurableFactory;
import org.jboss.xnio.FutureConnection;
import org.jboss.xnio.IoFuture;
import org.jboss.xnio.IoHandler;
import org.jboss.xnio.IoHandlerFactory;
import org.jboss.xnio.IoUtils;
import static org.jboss.xnio.IoUtils.nullHandler;
import static org.jboss.xnio.IoUtils.safeClose;
import org.jboss.xnio.Xnio;
import org.jboss.xnio.channels.BoundChannel;
import org.jboss.xnio.channels.BoundServer;
import org.jboss.xnio.channels.CommonOptions;
import org.jboss.xnio.channels.ConnectedStreamChannel;
import org.jboss.xnio.channels.TcpChannel;
import org.jboss.xnio.log.Logger;
import org.jboss.xnio.nio.NioXnio;
import org.jboss.xnio.nio.NioXnioConfiguration;
import org.jboss.xnio.test.support.LoggingHelper;
import org.jboss.xnio.test.support.TestThreadFactory;

/**
 *
 */
public final class NioTcpTestCase extends TestCase {
    static {
        LoggingHelper.init();
    }

    private static final Logger log = Logger.getLogger("TEST");

    private final TestThreadFactory threadFactory = new TestThreadFactory();

    private static final int SERVER_PORT = 12345;

    private void doConnectionTest(final Runnable body, final IoHandler<? super TcpChannel> clientHandler, final IoHandler<? super TcpChannel> serverHandler) throws Exception {
        final NioXnioConfiguration conf = new NioXnioConfiguration();
        conf.setSelectorThreadFactory(threadFactory);
        conf.setExecutor(new ThreadPoolExecutor(4, 10, 1000L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(50)));
        Xnio xnio = NioXnio.create(conf);
        try {
            final ConfigurableFactory<BoundServer<SocketAddress,BoundChannel<SocketAddress>>> serverFactory = xnio.createTcpServer(new IoHandlerFactory<TcpChannel>() {
                public IoHandler<? super TcpChannel> createHandler() {
                    return new CatchingHandler<TcpChannel>(serverHandler, threadFactory);
                }
            }, new SocketAddress[] { new InetSocketAddress(Inet4Address.getByAddress(new byte[] { 127, 0, 0, 1 }), SERVER_PORT)});
            serverFactory.setOption(CommonOptions.REUSE_ADDRESSES, Boolean.TRUE);
            final BoundServer<SocketAddress, BoundChannel<SocketAddress>> server = serverFactory.create();
            try {
                final ConfigurableFactory<CloseableTcpConnector> connectorFactory = xnio.createTcpConnector();
                final CloseableTcpConnector connector = connectorFactory.create();
                try {
                    final IoFuture<TcpChannel> ioFuture = connector.connectTo(new InetSocketAddress(Inet4Address.getByAddress(new byte[] { 127, 0, 0, 1 }), SERVER_PORT), new CatchingHandler<TcpChannel>(clientHandler, threadFactory));
                    final TcpChannel channel = ioFuture.get();
                    try {
                        body.run();
                        channel.close();
                        connector.close();
                        server.close();
                        xnio.close();
                    } finally {
                        safeClose(channel);
                    }
                } finally {
                    IoUtils.safeClose(connector);
                }
            } finally {
                IoUtils.safeClose(server);
            }
        } finally {
            IoUtils.safeClose(xnio);
        }
    }

    public void testTcpConnect() throws Exception {
        threadFactory.clear();
        log.info("Test: testTcpConnect");
        doConnectionTest(new Runnable() {
            public void run() {
            }
        }, nullHandler(), nullHandler());
        threadFactory.await();
    }

    public void testClientTcpClose() throws Exception {
        threadFactory.clear();
        log.info("Test: testClientTcpClose");
        final CountDownLatch latch = new CountDownLatch(2);
        final AtomicBoolean clientOK = new AtomicBoolean(false);
        final AtomicBoolean serverOK = new AtomicBoolean(false);
        doConnectionTest(new Runnable() {
            public void run() {
                try {
                    assertTrue(latch.await(500L, TimeUnit.MILLISECONDS));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, new IoHandler<ConnectedStreamChannel<SocketAddress>>() {
            public void handleOpened(final ConnectedStreamChannel<SocketAddress> channel) {
                log.info("In client open");
                try {
                    channel.close();
                    clientOK.set(true);
                } catch (Throwable t) {
                    t.printStackTrace();
                    latch.countDown();
                    throw new RuntimeException(t);
                }
            }

            public void handleReadable(final ConnectedStreamChannel<SocketAddress> channel) {
                log.info("In client readable");
            }

            public void handleWritable(final ConnectedStreamChannel<SocketAddress> channel) {
                log.info("In client writable");
            }

            public void handleClosed(final ConnectedStreamChannel<SocketAddress> channel) {
                log.info("In client close");
                latch.countDown();
            }
        }, new IoHandler<ConnectedStreamChannel<SocketAddress>>() {
            public void handleOpened(final ConnectedStreamChannel<SocketAddress> channel) {
                log.info("In server opened");
                channel.resumeReads();
            }

            public void handleReadable(final ConnectedStreamChannel<SocketAddress> channel) {
                log.info("In server readable");
                try {
                    final int c = channel.read(ByteBuffer.allocate(100));
                    if (c == -1) {
                        serverOK.set(true);
                    }
                    channel.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            public void handleWritable(final ConnectedStreamChannel<SocketAddress> channel) {
                log.info("In server writable");
            }

            public void handleClosed(final ConnectedStreamChannel<SocketAddress> channel) {
                log.info("In server closed");
                latch.countDown();
            }
        });
        assertTrue(serverOK.get());
        assertTrue(clientOK.get());
        threadFactory.await();
    }

    public void testServerTcpClose() throws Exception {
        threadFactory.clear();
        log.info("Test: testServerTcpClose");
        final CountDownLatch latch = new CountDownLatch(2);
        final AtomicBoolean clientOK = new AtomicBoolean(false);
{'fraction_non_alphanumeric': 0.08786290560037689, 'fraction_numerical': 0.006595606854719981, 'mean_word_length': 2.323938148365629, 'pattern_counts': {'":': 0, '<': 55, '<?xml version=': 0, '>': 55, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6614787', 'n_tokens_mistral': 4536, 'n_tokens_neox': 4238, 'n_words': 1061}