Package org.apache.mina.core.service

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


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

    public void testClientToServer() throws Exception {
        IoAcceptor acceptor = new VmPipeAcceptor();
        //acceptor.getFilterChain().addLast( "logger", new LoggingFilter() );

        IoConnector connector = new VmPipeConnector();
        //connector.getFilterChain().addLast( "logger", new LoggingFilter() );

        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();
            }
        });

        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

    /**
     * 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> bind0(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<IoSession>() {
            public void add(IoSession session) {
View Full Code Here

  @Inject
  private SshDaemon daemon;

  @Override
  protected void run() throws Failure {
    final IoAcceptor acceptor = daemon.getIoAcceptor();
    if (acceptor == null) {
      throw new Failure(1, "fatal: sshd no longer running");
    }

    final List<IoSession> list =
        new ArrayList<IoSession>(acceptor.getManagedSessions().values());
    Collections.sort(list, new Comparator<IoSession>() {
      @Override
      public int compare(IoSession arg0, IoSession arg1) {
        if (arg0.getCreationTime() < arg1.getCreationTime()) {
          return -1;
View Full Code Here

        // -------------------------------------------------------------------
        // 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

            endIndex = address.indexOf("/", beginIndex);
            int port = Integer.parseInt(address.substring(beginIndex + 1, endIndex));
            //System.out.println("hostName: " + hostName);
            //System.out.println("port: " + port);
           
            IoAcceptor acceptor = new NioSocketAcceptor();
            acceptor.getFilterChain().addLast("logger", new LoggingFilter());
            //acceptor.getFilterChain().addLast("LowLevelProtocol", new SoapTcpIoFilter());
            acceptor.getFilterChain().addLast("HighLevelProtocol",
                                              new ProtocolCodecFilter(new SoapTcpCodecFactory()));
            acceptor.setDefaultLocalAddress(new InetSocketAddress(port));
            acceptor.setHandler(this);
            acceptor.bind();
            System.out.println("server is listenig at port " + port);
        }
    }
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

        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

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.