Package org.apache.mina.core.service

Examples of org.apache.mina.core.service.IoAcceptor


        // -------------------------------------------------------------------
        // handle the body of this operation below here
        // -------------------------------------------------------------------

        IoAcceptor acceptor = ( IoAcceptor ) requestor.getIoSession().getService();
        List<IoSession> sessions = new ArrayList<IoSession>(
            acceptor.getManagedSessions().values() );

        // build the graceful disconnect message with replicationContexts
        GracefulDisconnectResponse notice = getGracefulDisconnect( req.getTimeOffline(), req.getDelay() );

        // send (synch) the GracefulDisconnect to each client before unbinding
        sendGracefulDisconnect( sessions, notice, requestor.getIoSession() );

        // wait for the specified delay before we unbind the service
        waitForDelay( req.getDelay() );

        // -------------------------------------------------------------------
        // unbind the server socket for the LDAP service here so no new
        // connections are accepted while we process this shutdown request
        // note that the following must be issued before binding the ldap
        // service in order to prevent client disconnects on service unbind:
        //
        // minaRegistry.getAcceptor( service.getTransportType() )
        //                       .setDisconnectClientsOnUnbind( false );
        // -------------------------------------------------------------------
        // This might not work, either.
        acceptor.unbind( requestor.getIoSession().getServiceAddress() );

        // -------------------------------------------------------------------
        // synchronously send a NoD to clients that are not aware of this resp
        // after sending the NoD the client is disconnected if still connected
        // -------------------------------------------------------------------
View Full Code Here


    /**
     * Creates a new instance.
     */
    public DummySession() {
        // Initialize dummy service.
        IoAcceptor acceptor = new AbstractIoAcceptor(
                new AbstractIoSessionConfig() {
                    @Override
                    protected void doSetAll(IoSessionConfig config) {
                        // Do nothing
                    }
                },
                new Executor() {
                    public void execute(Runnable command) {
                        // Do nothing
                    }
                }) {

            @Override
            protected Set<SocketAddress> bindInternal(List<? extends SocketAddress> localAddresses) throws Exception {
                throw new UnsupportedOperationException();
            }

            @Override
            protected void unbind0(List<? extends SocketAddress> localAddresses) throws Exception {
                throw new UnsupportedOperationException();
            }

            public IoSession newSession(SocketAddress remoteAddress, SocketAddress localAddress) {
                throw new UnsupportedOperationException();
            }

            public TransportMetadata getTransportMetadata() {
                return TRANSPORT_METADATA;
            }

            @Override
            protected IoFuture dispose0() throws Exception {
                return null;
            }
        };

        // Set meaningless default values.
        acceptor.setHandler(new IoHandlerAdapter());

        service = acceptor;

        processor = new IoProcessor<AbstractIoSession>() {
            public void add(AbstractIoSession session) {
View Full Code Here

*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class VmPipeEventOrderTest extends TestCase {
    public void testServerToClient() throws Exception {
        IoAcceptor acceptor = new VmPipeAcceptor();
        IoConnector connector = new VmPipeConnector();

        acceptor.setHandler(new IoHandlerAdapter() {
            @Override
            public void sessionOpened(IoSession session) throws Exception {
                session.write("B");
            }

            @Override
            public void messageSent(IoSession session, Object message)
                    throws Exception {
                session.close(true);
            }
        });

        acceptor.bind(new VmPipeAddress(1));

        final StringBuffer actual = new StringBuffer();

        connector.setHandler(new IoHandlerAdapter() {

            @Override
            public void messageReceived(IoSession session, Object message)
                    throws Exception {
                actual.append(message);
            }

            @Override
            public void sessionClosed(IoSession session) throws Exception {
                actual.append("C");
            }

            @Override
            public void sessionOpened(IoSession session) throws Exception {
                actual.append("A");
            }

        });

        ConnectFuture future = connector.connect(new VmPipeAddress(1));

        future.awaitUninterruptibly();
        future.getSession().getCloseFuture().awaitUninterruptibly();
        acceptor.dispose();

        // sessionClosed() might not be invoked yet
        // even if the connection is closed.
        while (actual.indexOf("C") < 0) {
            Thread.yield();
View Full Code Here

        Assert.assertEquals("ABC", actual.toString());
    }

    public void testClientToServer() throws Exception {
        IoAcceptor acceptor = new VmPipeAcceptor();
        IoConnector connector = new VmPipeConnector();

        final StringBuffer actual = new StringBuffer();

        acceptor.setHandler(new IoHandlerAdapter() {

            @Override
            public void messageReceived(IoSession session, Object message)
                    throws Exception {
                actual.append(message);
            }

            @Override
            public void sessionClosed(IoSession session) throws Exception {
                actual.append("C");
            }

            @Override
            public void sessionOpened(IoSession session) throws Exception {
                actual.append("A");
            }

        });

        acceptor.bind(new VmPipeAddress(1));

        connector.setHandler(new IoHandlerAdapter() {
            @Override
            public void sessionOpened(IoSession session) throws Exception {
                session.write("B");
            }

            @Override
            public void messageSent(IoSession session, Object message)
                    throws Exception {
                session.close(true);
            }
        });

        ConnectFuture future = connector.connect(new VmPipeAddress(1));

        future.awaitUninterruptibly();
        future.getSession().getCloseFuture().awaitUninterruptibly();
        acceptor.dispose();
        connector.dispose();

        // sessionClosed() might not be invoked yet
        // even if the connection is closed.
        while (actual.indexOf("C") < 0) {
View Full Code Here

        final VmPipeAddress address = new VmPipeAddress(1);
        final IoConnector connector = new VmPipeConnector();
        final AtomicReference<IoSession> c1 = new AtomicReference<IoSession>();
        final CountDownLatch latch = new CountDownLatch(1);
        final CountDownLatch messageCount = new CountDownLatch(2);
        IoAcceptor acceptor = new VmPipeAcceptor();

        acceptor.setHandler(new IoHandlerAdapter() {
            @Override
            public void messageReceived(IoSession session, Object message) throws Exception {
                //System.out.println(Thread.currentThread().getName() + ": " + message);

                if ("start".equals(message)) {
                    session.write("open new");
                } else if ("re-use c1".equals(message)) {
                    session.write("tell me something on c1 now");
                } else if (((String) message).startsWith("please don't deadlock")) {
                    messageCount.countDown();
                } else {
                    fail("unexpected message received " + message);
                }
            }
        });
        acceptor.bind(address);

        connector.setHandler(new IoHandlerAdapter() {
            @Override
            public void messageReceived(IoSession session, Object message) throws Exception {
                //System.out.println(Thread.currentThread().getName() + ": " + message);

                if ("open new".equals(message)) {
                    //System.out.println("opening c2 from " + Thread.currentThread().getName());

                    IoConnector c2 = new VmPipeConnector();
                    c2.setHandler(new IoHandlerAdapter() {
                        @Override
                        public void sessionOpened(IoSession session) throws Exception {
                            session.write("re-use c1");
                        }

                        @Override
                        public void messageReceived(IoSession session, Object message) throws Exception {
                            //System.out.println(Thread.currentThread().getName() + ": " + message);

                            if ("tell me something on c1 now".equals(message)) {
                                latch.countDown();
                                c1.get().write("please don't deadlock via c1");
                            } else {
                                fail("unexpected message received " + message);
                            }
                        }
                    });

                    ConnectFuture c2Future = c2.connect(address);

                    c2Future.await();

                    latch.await();

                    c2Future.getSession().write("please don't deadlock via c2");
                } else {
                    fail("unexpeced message received " + message);
                }
            }
        });

        ConnectFuture future = connector.connect(address);

        future.await();

        c1.set(future.getSession());
        c1.get().write("start");

        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();

        while (!messageCount.await(100, TimeUnit.MILLISECONDS)) {
            long[] threads = threadMXBean.findMonitorDeadlockedThreads();

            if (null != threads) {
                StringBuffer sb = new StringBuffer(256);
                ThreadInfo[] infos = threadMXBean.getThreadInfo(threads, Integer.MAX_VALUE);

                for (ThreadInfo info : infos) {
                    sb.append(info.getThreadName())
                            .append(" blocked on ")
                            .append(info.getLockName())
                            .append(" owned by ")
                            .append(info.getLockOwnerName())
                            .append("\n");
                }

                for (ThreadInfo info : infos) {
                    sb.append("\nStack for ").append(info.getThreadName()).append("\n");
                    for (StackTraceElement element : info.getStackTrace()) {
                        sb.append("\t").append(element).append("\n");
                    }
                }

                fail("deadlocked! \n" + sb);
            }
        }

        acceptor.setCloseOnDeactivation(false);
        acceptor.dispose();
    }
View Full Code Here

        final CountDownLatch latch = new CountDownLatch(1);
        final boolean[] success = {false};
        final Throwable[] exception = {null};
       
        int port = AvailablePortFinder.getNextAvailable(1025);
        IoAcceptor acceptor = createAcceptor();
        acceptor.setHandler(new IoHandlerAdapter() {
            private int index = 0;
            @Override
            public void exceptionCaught(IoSession session, Throwable cause)
                    throws Exception {
                exception[0] = cause;
                session.close(true);
            }
            @Override
            public void messageReceived(IoSession session, Object message) throws Exception {
                IoBuffer buffer = (IoBuffer) message;
                while (buffer.hasRemaining()) {
                    int x = buffer.getInt();
                    if (x != index) {
                        throw new Exception(String.format("Integer at %d was %d but should have been %d", index, x, index));
                    }
                    index++;
                }
                if (index > FILE_SIZE / 4) {
                    throw new Exception("Read too much data");
                }
                if (index == FILE_SIZE / 4) {
                    success[0] = true;
                    session.close(true);
                }
            }
        });
        acceptor.bind(new InetSocketAddress(port));
       
        IoConnector connector = createConnector();
        connector.setHandler(new IoHandlerAdapter() {
            @Override
            public void exceptionCaught(IoSession session, Throwable cause)
                    throws Exception {
                exception[0] = cause;
                session.close(true);
            }
            @Override
            public void sessionClosed(IoSession session) throws Exception {
                latch.countDown();
            }
        });
        ConnectFuture future = connector.connect(new InetSocketAddress("localhost", port));
        future.awaitUninterruptibly();
       
        IoSession session = future.getSession();
        session.write(file);
       
        latch.await();
       
        if (exception[0] != null) {
            throw exception[0];
        }
        assertTrue("Did not complete file transfer successfully", success[0]);
       
        assertEquals("Written messages should be 1 (we wrote one file)", 1, session.getWrittenMessages());
        assertEquals("Written bytes should match file size", FILE_SIZE, session.getWrittenBytes());
       
        connector.dispose();
        acceptor.dispose();
    }
View Full Code Here

    protected abstract IoAcceptor createAcceptor();
    protected abstract IoConnector createConnector();

    public void testConnectFutureSuccessTiming() throws Exception {
        int port = AvailablePortFinder.getNextAvailable(2025);
        IoAcceptor acceptor = createAcceptor();
        acceptor.setHandler(new IoHandlerAdapter());
        acceptor.bind(new InetSocketAddress(port));

        try {
            final StringBuffer buf = new StringBuffer();
            IoConnector connector = createConnector();
            connector.setHandler(new IoHandlerAdapter() {
                @Override
                public void sessionCreated(IoSession session) {
                    buf.append("1");
                }

                @Override
                public void sessionOpened(IoSession session) {
                    buf.append("2");
                }

                @Override
                public void exceptionCaught(IoSession session, Throwable cause) {
                    buf.append("X");
                }
            });
            ConnectFuture future = connector.connect(new InetSocketAddress(
                    "localhost", port));
            future.awaitUninterruptibly();
            buf.append("3");
            future.getSession().close(true);
            // sessionCreated() will fire before the connect future completes
            // but sessionOpened() may not
            Assert.assertTrue(Pattern.matches("12?32?", buf.toString()));
        } finally {
            acceptor.dispose();
        }
    }
View Full Code Here

        final boolean[] assertions = {false, false, false};
        final CountDownLatch latch = new CountDownLatch(2);
        final ConnectFuture[] callbackFuture = new ConnectFuture[1];
       
        int port = AvailablePortFinder.getNextAvailable(4025);
        IoAcceptor acceptor = createAcceptor();
        acceptor.setHandler(new IoHandlerAdapter());
        InetSocketAddress address = new InetSocketAddress(port);
        acceptor.bind(address);

        IoConnector connector = createConnector();
        connector.setHandler(new IoHandlerAdapter() {
           @Override
            public void sessionCreated(IoSession session) throws Exception {
View Full Code Here

                    }

                });
        connector.setHandler(new IoHandlerAdapter());

        IoAcceptor acceptor = new NioSocketAcceptor();
        acceptor.setHandler(new IoHandlerAdapter());

        InetSocketAddress addr = new InetSocketAddress("localhost",
                AvailablePortFinder.getNextAvailable(20000));

        acceptor.bind(addr);
        ConnectFuture future = connector.connect(addr);
        future.awaitUninterruptibly();
        IoSession session = future.getSession();
        WriteFuture wf = session.write(IoBuffer.allocate(1)).awaitUninterruptibly();
        assertNotNull(wf.getException());

        connector.dispose();
        acceptor.dispose();
    }
View Full Code Here

    /**
     * Creates a new instance.
     */
    public DummySession() {
        // Initialize dummy service.
        IoAcceptor acceptor = new AbstractIoAcceptor(
                new AbstractIoSessionConfig() {
                    @Override
                    protected void doSetAll(IoSessionConfig config) {}
                },
                new Executor() {
                    public void execute(Runnable command) {}
                }) {

            @Override
            protected Set<SocketAddress> bindInternal(List<? extends SocketAddress> localAddresses) throws Exception {
                throw new UnsupportedOperationException();
            }

            @Override
            protected void unbind0(List<? extends SocketAddress> localAddresses) throws Exception {
                throw new UnsupportedOperationException();
            }

            public IoSession newSession(SocketAddress remoteAddress, SocketAddress localAddress) {
                throw new UnsupportedOperationException();
            }

            public TransportMetadata getTransportMetadata() {
                return TRANSPORT_METADATA;
            }

            @Override
            protected IoFuture dispose0() throws Exception {
                return null;
            }
        };

        // Set meaningless default values.
        acceptor.setHandler(new IoHandlerAdapter());

        service = acceptor;

        processor = new IoProcessor<AbstractIoSession>() {
            public void add(AbstractIoSession session) {
View Full Code Here

TOP

Related Classes of org.apache.mina.core.service.IoAcceptor

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.