Package org.apache.mina.core.service

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


        tasksReady,
        tasksSleeping);
  }

  private void sshSummary() {
    IoAcceptor acceptor = daemon.getIoAcceptor();
    if (acceptor == null) {
      return;
    }

    long now = System.currentTimeMillis();
    Collection<IoSession> list = acceptor.getManagedSessions().values();
    long oldest = now;
    for (IoSession s : list) {
      oldest = Math.min(oldest, s.getCreationTime());
    }
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();
        IoConnector connector = createConnector();

        try {
            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);
                    }
                }
            });
           
            ((NioSocketAcceptor)acceptor).setReuseAddress(true);
           
            acceptor.bind(new InetSocketAddress(port));
           
            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());
        } finally {
            try {
                connector.dispose();
            } finally {
                acceptor.dispose();
            }
        }
    }
View Full Code Here

    protected abstract IoConnector createConnector();

    @Test
    public void testConnectFutureSuccessTiming() throws Exception {
        int port = AvailablePortFinder.getNextAvailable(1025);
        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
            assertTrue(Pattern.matches("12?32?", buf.toString()));
        } finally {
            acceptor.dispose();
        }
    }
View Full Code Here

        final CountDownLatch latch = new CountDownLatch(2);
        final ConnectFuture[] callbackFuture = new ConnectFuture[1];
       
        int port = AvailablePortFinder.getNextAvailable(1025);

        IoAcceptor acceptor = createAcceptor();
        IoConnector connector = createConnector();

        try {
            acceptor.setHandler(new IoHandlerAdapter());
            InetSocketAddress address = new InetSocketAddress(port);
            acceptor.bind(address);
   
            connector.setHandler(new IoHandlerAdapter() {
               @Override
                public void sessionCreated(IoSession session) throws Exception {
                       assertions[sessionCreatedInvoked] = true;
                       assertions[sessionCreatedInvokedBeforeCallback] = !assertions[callbackInvoked];
                       latch.countDown();
                }
            });
       
            ConnectFuture future = connector.connect(new InetSocketAddress("127.0.0.1", port), new IoSessionInitializer<ConnectFuture>() {
                public void initializeSession(IoSession session, ConnectFuture future) {
                    assertions[callbackInvoked] = true;
                    callbackFuture[0] = future;
                    latch.countDown();
                }
            });
           
            assertTrue("Timed out waiting for callback and IoHandler.sessionCreated to be invoked", latch.await(5, TimeUnit.SECONDS));
            assertTrue("Callback was not invoked", assertions[callbackInvoked]);
            assertTrue("IoHandler.sessionCreated was not invoked", assertions[sessionCreatedInvoked]);
            assertFalse("IoHandler.sessionCreated was invoked before session callback", assertions[sessionCreatedInvokedBeforeCallback]);
            assertSame("Callback future should have been same future as returned by connect", future, callbackFuture[0]);
        } finally {
            try {
                connector.dispose();
            } finally {
                acceptor.dispose();
            }
        }
    }
View Full Code Here

* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class VmPipeEventOrderTest {
    @Test
    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

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

    @Test
    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

        assertNull(support.getManagedSessions().get(session.getId()));
    }

    @Test
    public void testDisconnectOnUnbind() throws Exception {
        IoAcceptor acceptor = EasyMock.createStrictMock(IoAcceptor.class);

        final IoServiceListenerSupport support = new IoServiceListenerSupport(
                acceptor);

        final DummySession session = new DummySession();
        session.setService(acceptor);
        session.setLocalAddress(ADDRESS);

        IoHandler handler = EasyMock.createStrictMock(IoHandler.class);
        session.setHandler(handler);

        final IoServiceListener listener = EasyMock.createStrictMock(IoServiceListener.class);

        // Activate a service and create a session.
        listener.serviceActivated(acceptor);
        listener.sessionCreated(session);
        handler.sessionCreated(session);
        handler.sessionOpened(session);

        EasyMock.replay(listener);
        EasyMock.replay(handler);

        support.add(listener);
        support.fireServiceActivated();
        support.fireSessionCreated(session);

        EasyMock.verify(listener);
        EasyMock.verify(handler);

        // Deactivate a service and make sure the session is closed & destroyed.
        EasyMock.reset(listener);
        EasyMock.reset(handler);

        listener.serviceDeactivated(acceptor);
        EasyMock.expect(acceptor.isCloseOnDeactivation()).andReturn(true);
        listener.sessionDestroyed(session);
        handler.sessionClosed(session);

        EasyMock.replay(listener);
        EasyMock.replay(acceptor);
View Full Code Here

                throw new NoRouteToHostException("No Route To Host Test");
            }
        });
        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

        assertNull(support.getManagedSessions().get(session.getId()));
    }

    @Test
    public void testDisconnectOnUnbind() throws Exception {
        IoAcceptor acceptor = EasyMock.createStrictMock(IoAcceptor.class);

        final IoServiceListenerSupport support = new IoServiceListenerSupport(acceptor);

        final DummySession session = new DummySession();
        session.setService(acceptor);
        session.setLocalAddress(ADDRESS);

        IoHandler handler = EasyMock.createStrictMock(IoHandler.class);
        session.setHandler(handler);

        final IoServiceListener listener = EasyMock.createStrictMock(IoServiceListener.class);

        // Activate a service and create a session.
        listener.serviceActivated(acceptor);
        listener.sessionCreated(session);
        handler.sessionCreated(session);
        handler.sessionOpened(session);

        EasyMock.replay(listener);
        EasyMock.replay(handler);

        support.add(listener);
        support.fireServiceActivated();
        support.fireSessionCreated(session);

        EasyMock.verify(listener);
        EasyMock.verify(handler);

        // Deactivate a service and make sure the session is closed & destroyed.
        EasyMock.reset(listener);
        EasyMock.reset(handler);

        listener.serviceDeactivated(acceptor);
        EasyMock.expect(acceptor.isCloseOnDeactivation()).andReturn(true);
        listener.sessionDestroyed(session);
        handler.sessionClosed(session);

        EasyMock.replay(listener);
        EasyMock.replay(acceptor);
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.