Java Code Examples for org.apache.mina.common.IoSession#close()

The following examples show how to use org.apache.mina.common.IoSession#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ExecutionVenueServerHandler.java    From cougar with Apache License 2.0 6 votes vote down vote up
@Override
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
    if (cause instanceof IOException) {
        ioExceptions.incrementAndGet();

        // We arrive here when the output pipe is broken. Broken network connections are not
        // really exceptional and should not be reported by dumping the stack trace.
        // Instead a summary debug level log message with some relevant info
        sessionLogger.log(ALL, session, "ExecutionVenueServerHandler: IOException received on session - closing");
    } else {
        otherExceptions.incrementAndGet();
        sessionLogger.log(SESSION, session, "ExecutionVenueServerHandler: Unexpected exception from session - see main log for details");
        LOG.warn("Unexpected exception from session " + NioUtils.getSessionId(session), cause);
    }
    session.close();
}
 
Example 2
Source File: CougarProtocolTest.java    From cougar with Apache License 2.0 6 votes vote down vote up
@Test
public void testConnect() throws IOException {
    boolean success = false;
    ExecutionVenueNioServer server = createServer(defaultServerConfig);
    try {
        server.start();
        server.setHealthState(true);

        IoSession session = createClient(defaultClientConfig, new IoHandlerAdapter() {
        });
        ClientHandshake handshake = (ClientHandshake) session.getAttribute(ClientHandshake.HANDSHAKE);
        handshake.await(10000);

        success = handshake.successful();

        session.close();
    }
    finally {
        server.stop();
    }

    assertEquals("connection was not successful", true, success);

}
 
Example 3
Source File: CougarProtocolTest.java    From cougar with Apache License 2.0 6 votes vote down vote up
@Test
public void testRejectionServerUnhealthy() throws IOException {
    ExecutionVenueNioServer server = createServer(defaultServerConfig);
    server.start();
    server.setHealthState(false);

    IoSession session = createClient(defaultClientConfig, new IoHandlerAdapter());

    ClientHandshake handshake = (ClientHandshake) session.getAttribute(ClientHandshake.HANDSHAKE);
    handshake.await(10000);

    boolean success = handshake.successful();

    session.close();
    server.stop();

    assertEquals("connection shouln't have been successful", false, success);
}
 
Example 4
Source File: SessionWriteQueueMonitoring.java    From cougar with Apache License 2.0 6 votes vote down vote up
@Override
public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception {
    // if we want to terminate based on queue depth then check it..
    SessionWriteQueueMonitor monitor = monitors.get(NioUtils.getSessionId(session));
    if (monitor != null) {
        long newDepth = monitor.countIn();
        if (maxWriteQueueSize > 0 && newDepth > maxWriteQueueSize) {
            logger.log(NioLogger.LoggingLevel.SESSION, session, "Session exceeded max writeQueue size of %s, closing session", maxWriteQueueSize);
            // kill
            session.close();
            return;
        }
    }

    nextFilter.filterWrite(session, writeRequest);
}
 
Example 5
Source File: CougarProtocol3.java    From cougar with Apache License 2.0 6 votes vote down vote up
@Override
public void sessionIdle(NextFilter nextFilter, IoSession session, IdleStatus status) throws Exception {
    try {
        if (status == IdleStatus.WRITER_IDLE) {
            nioLogger.log(PROTOCOL, session, "CougarProtocolCodecFilter: sending KEEP_ALIVE");
            session.write(KEEP_ALIVE);
            heartbeatsSent.incrementAndGet();
        } else {
            nioLogger.log(PROTOCOL, session, "CougarProtocolCodecFilter: KEEP_ALIVE timeout closing session");
            session.close();
            heartbeatsMissed.incrementAndGet();
        }
    } finally {
        nextFilter.sessionIdle(session, status);
    }
}
 
Example 6
Source File: CougarProtocolTest.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Test
public void testKeepAliveNotRecieved() throws InterruptedException, IOException {
    defaultServerConfig.setKeepAliveInterval(2);
    defaultServerConfig.setKeepAliveTimeout(1);
    ExecutionVenueNioServer server = createServer(defaultServerConfig);
    server.start();
    server.setHealthState(true);

    defaultClientConfig.setKeepAliveInterval(2);
    defaultClientConfig.setKeepAliveTimeout(1);

    final CountDownLatch cdl = new CountDownLatch(1);
    IoSession ioSession = createClient(defaultClientConfig, new IoHandlerAdapter() {

        @Override
        public void sessionClosed(IoSession session) throws Exception {
            cdl.countDown();
        }
    });

    boolean closed = cdl.await(20000, TimeUnit.MILLISECONDS);

    ioSession.close();
    server.stop();

    assertEquals("Expecting session to be closed", true, closed);

}
 
Example 7
Source File: CougarProtocolTest.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Test
public void testKeepAlive() throws IOException, InterruptedException {
    defaultServerConfig.setKeepAliveInterval(1);
    defaultServerConfig.setKeepAliveTimeout(2);
    ExecutionVenueNioServer server = createServer(defaultServerConfig);
    server.start();
    server.setHealthState(true);

    defaultClientConfig.setKeepAliveInterval(1);
    defaultServerConfig.setKeepAliveTimeout(2);

    final CountDownLatch cdl = new CountDownLatch(1);
    IoSession ioSession = createClient(defaultClientConfig, new IoHandlerAdapter() {

        @Override
        public void sessionClosed(IoSession session) throws Exception {
            cdl.countDown();
        }
    });

    boolean closed = cdl.await(3, TimeUnit.SECONDS);
    ioSession.close();
    server.stop();


    assertEquals("session closed unexpected", false, closed);

}
 
Example 8
Source File: CougarProtocolTest.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Test
public void testReject() throws IOException {
    // force version to an unsupported one (the next one)
    CougarProtocol.setMinClientProtocolVersion((byte) (CougarProtocol.TRANSPORT_PROTOCOL_VERSION_MAX_SUPPORTED + 1));
    CougarProtocol.setMaxClientProtocolVersion((byte) (CougarProtocol.TRANSPORT_PROTOCOL_VERSION_MAX_SUPPORTED + 1));
    try {
        TlsNioConfig nioConfig = new TlsNioConfig();
        nioConfig.setNioLogger(new NioLogger("ALL"));

        nioConfig.setListenAddress("127.0.0.1");
        nioConfig.setListenPort(2227);
        nioConfig.setReuseAddress(true);
        nioConfig.setTcpNoDelay(true);
        nioConfig.setKeepAliveInterval(Integer.MAX_VALUE);
        nioConfig.setKeepAliveTimeout(Integer.MAX_VALUE);
        ExecutionVenueNioServer server = createServer(nioConfig);
        server.start();
        server.setHealthState(true);

        IoSession ioSession = createClient(defaultClientConfig, new IoHandlerAdapter());

        ClientHandshake handshake = (ClientHandshake) ioSession.getAttribute(ClientHandshake.HANDSHAKE);
        handshake.await(10000);

        boolean success = handshake.successful();

        ioSession.close();
        server.stop();

        assertEquals("connection shouldn't have been successful", false, success);
    } finally {
        CougarProtocol.setMinClientProtocolVersion(CougarProtocol.TRANSPORT_PROTOCOL_VERSION_MAX_SUPPORTED);
        CougarProtocol.setMaxClientProtocolVersion(CougarProtocol.TRANSPORT_PROTOCOL_VERSION_MAX_SUPPORTED);
    }

}
 
Example 9
Source File: CougarProtocolTest.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Test
public void testDisconnect() throws IOException, InterruptedException {
    ExecutionVenueNioServer server = createServer(defaultServerConfig);
    boolean closed = false;
    try {
        server.start();
        server.setHealthState(true);

        final CountDownLatch cdl = new CountDownLatch(1);
        IoSession ioSession = createClient(defaultClientConfig, new IoHandlerAdapter() {
            @Override
            public void sessionClosed(IoSession session) throws Exception {
                cdl.countDown();
            }
        });

        ClientHandshake handshake = (ClientHandshake) ioSession.getAttribute(ClientHandshake.HANDSHAKE);
        handshake.await(1000);

        boolean success = handshake.successful();

        assertEquals("connection should have been successful", true, success);

        server.setHealthState(false);

        closed = cdl.await(50, TimeUnit.SECONDS);

        ioSession.close();
    }
    finally {
        server.stop();
    }


    assertEquals("expected session to close due to disconnection", true, closed);

}
 
Example 10
Source File: RequestResponseManagerImpl.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Override
public void exceptionCaught(IoSession session, Throwable cause) {
    if (cause instanceof IOException) {
        LOG.debug("IO exception from session "+NioUtils.getSessionId(session), cause);
    } else {
        LOG.warn("Unexpected exception from session "+NioUtils.getSessionId(session), cause);
    }
    nioLogger.log(NioLogger.LoggingLevel.SESSION, session, "RequestResponseManager - %s received: %s - closing session", cause.getClass().getSimpleName(), cause.getMessage());
    session.close();
}
 
Example 11
Source File: ClientConnectedObjectManager.java    From cougar with Apache License 2.0 5 votes vote down vote up
public void terminateSubscription(IoSession session, long heapId, String subscriptionId, Subscription.CloseReason reason) {
    heapSubMutationLock.lock();
    try {
        String sessionId = NioUtils.getSessionId(session);
        ConnectedHeaps heaps = heapsByServer.get(NioUtils.getSessionId(session));
        if (heaps != null) {
            HeapState heapState = heaps.getHeapState(heapId);
            if (heapState != null) {
                nioLogger.log(NioLogger.LoggingLevel.TRANSPORT, sessionId, "Subscription termination received for subscription %s with reason %s", subscriptionId, reason);
                if (reason == Subscription.CloseReason.REQUESTED_BY_SUBSCRIBER || reason == Subscription.CloseReason.REQUESTED_BY_SUBSCRIBER_ADMINISTRATOR) {
                    try {
                        nioLogger.log(NioLogger.LoggingLevel.TRANSPORT, session, "Notifying server that client wants to terminate subscription %s", subscriptionId);
                        NioUtils.writeEventMessageToSession(session, new TerminateSubscription(heapId, subscriptionId, reason.name()), objectIOFactory);
                    } catch (Exception ioe) {
                        // if we can't write to the stream to tell the server that the client wants to unsub, then it's likely the session is already
                        // gone. however, we'll log a message to let people know and then request a close of the session to make sure.
                        nioLogger.log(NioLogger.LoggingLevel.SESSION, session, "Error occurred whilst trying to inform server of subscription termination, closing session");
                        LOGGER.info("Error occurred whilst trying to inform server of subscription termination, closing session", ioe);
                        session.close();
                    }
                }

                heapState.terminateSubscription(subscriptionId, reason);
                nioLogger.log(NioLogger.LoggingLevel.TRANSPORT, sessionId, "Subscription terminated for heapId = %s and subscriptionId = %s", heapId, subscriptionId);

                if (heapState.getSubscriptions().isEmpty()) {
                    terminateSubscriptions(sessionId, heapId, Subscription.CloseReason.INTERNAL_ERROR); // if there's something found by this then it's an internal error.
                }
            }
        }
    } finally {
        heapSubMutationLock.unlock();
    }
}
 
Example 12
Source File: PooledServerConnectedObjectManager.java    From cougar with Apache License 2.0 4 votes vote down vote up
/**
 * Terminates a single subscription to a single heap
 */
public void terminateSubscription(IoSession session, String heapUri, String subscriptionId, Subscription.CloseReason reason) {
    Lock heapUpdateLock = null;
    try {
        HeapState state = heapStates.get(heapUri);
        if (state != null) {
            heapUpdateLock = state.getUpdateLock();
            heapUpdateLock.lock();
        }
        subTermLock.lock();

        if (state != null) {
            if (!state.isTerminated()) {
                state.terminateSubscription(session, subscriptionId, reason);
                // notify client
                if (reason == REQUESTED_BY_PUBLISHER || reason == Subscription.CloseReason.REQUESTED_BY_PUBLISHER_ADMINISTRATOR) {
                    try {
                        nioLogger.log(NioLogger.LoggingLevel.TRANSPORT, session, "Notifying client that publisher has terminated subscription %s", subscriptionId);
                        NioUtils.writeEventMessageToSession(session, new TerminateSubscription(state.getHeapId(), subscriptionId, reason.name()), objectIOFactory);
                    } catch (Exception e) {
                        // if we can't tell them about it then something more serious has just happened.
                        // the client will likely find out anyway since this will likely mean a dead session
                        // we'll just log some info to the log to aid any debugging. We won't change the closure reason.
                        LOGGER.info("Error occurred whilst trying to inform client of subscription termination", e);
                        nioLogger.log(NioLogger.LoggingLevel.SESSION, session, "Error occurred whilst trying to inform client of subscription termination, closing session");
                        // we'll request a closure of the session too to make sure everything gets cleaned up, although chances are it's already closed
                        session.close();
                    }
                }

                if (state.hasSubscriptions()) {
                    terminateSubscriptions(heapUri, reason);
                } else if (state.getSubscriptions(session).isEmpty()) {
                    terminateSubscriptions(session, heapUri, reason);
                }
            }
        }

        Multiset<String> heapsForSession = heapsByClient.get(session);
        if (heapsForSession != null) {
            heapsForSession.remove(heapUri);
            if (heapsForSession.isEmpty()) {
                terminateSubscriptions(session, reason);
            }
        }
    } finally {
        subTermLock.unlock();
        if (heapUpdateLock != null) {
            heapUpdateLock.unlock();
        }
    }
}
 
Example 13
Source File: TestServerHandler.java    From cougar with Apache License 2.0 4 votes vote down vote up
public void exceptionCaught(IoSession session, Throwable t) throws Exception {
	t.printStackTrace();
	session.close();
}
 
Example 14
Source File: CougarProtocolTest.java    From cougar with Apache License 2.0 4 votes vote down vote up
@Test
public void testGracefulDisconnect() throws IOException, InterruptedException {
    ExecutionVenueNioServer server = createServer(defaultServerConfig);
    server.start();
    server.setHealthState(true);

    final CountDownLatch cdl = new CountDownLatch(1);
    IoSession ioSession = createClient(defaultClientConfig, new IoHandlerAdapter() {
        @Override
        public void sessionClosed(IoSession session) throws Exception {
            cdl.countDown();
        }
    });

    ClientHandshake handshake = (ClientHandshake) ioSession.getAttribute(ClientHandshake.HANDSHAKE);
    handshake.await(1000);

    boolean success = handshake.successful();

    assertEquals("connection should have been successful", true, success);

    // write some dummy request
    ioSession.write(new RequestMessage(1, "request".getBytes()));

    server.setHealthState(false);

    boolean closed = cdl.await(50, TimeUnit.SECONDS);

    // Suspend message should have been recieved
    assertTrue(ioSession.containsAttribute(ProtocolMessage.ProtocolMessageType.SUSPEND.name()));
    // Disconnect message should have been recieved
    assertTrue(ioSession.containsAttribute(ProtocolMessage.ProtocolMessageType.DISCONNECT.name()));
    // Session should have been disconnected
    assertFalse(ioSession.isConnected());

    // teardown
    ioSession.close();
    server.stop();

    assertEquals("expected session to close due to disconnection", true, closed);

}