org.apache.mina.common.IoSession Java Examples

The following examples show how to use org.apache.mina.common.IoSession. 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: 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 #2
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 #3
Source File: PooledServerConnectedObjectManager.java    From cougar with Apache License 2.0 6 votes vote down vote up
private void terminateAllSubscriptions(Subscription.CloseReason reason) {
    if (heapsByClient != null) {
        List<IoSession> sessions;
        try {
            subTermLock.lock();
            // take a copy in case it's being modified as we shutdown
            sessions = new ArrayList<IoSession>(heapsByClient.keySet());
        } finally {
            subTermLock.unlock();
        }

        for (IoSession session : sessions) {
            terminateSubscriptions(session, reason);
        }
    }
}
 
Example #4
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 #5
Source File: ClientConnectedObjectManagerTest.java    From cougar with Apache License 2.0 6 votes vote down vote up
@Test
public void firstSubscriptionInitialUpdateReceivedLate() throws Exception {
    NewHeapSubscription newHeapSubscription = new NewHeapSubscription(1, "sub1", "firstSubscriptionInitialUpdateReceivedLate");
    InvocationResponse response = new InvocationResponseImpl(newHeapSubscription);
    WaitingObserver observer = new WaitingObserver();

    IoSession session = new MyIoSession(String.valueOf(ioSessionId++));
    subject.handleSubscriptionResponse(session, response, observer);

    assertTrue(observer.await(1000L));
    assertTrue(observer.getExecutionResult().isFault());

    HeapDelta delta = new HeapDelta(1, 0, createUpdateList(createInitial(new InstallRoot(0, NodeType.SCALAR), new SetScalar(0, true))));
    subject.applyDelta(session, delta);

    assertNull(subject.getHeapsByServer().get(NioUtils.getSessionId(session)));
}
 
Example #6
Source File: PooledServerConnectedObjectManager.java    From cougar with Apache License 2.0 6 votes vote down vote up
public String addSubscription(LogExtension logExtension, Subscription subscription, IoSession session) {
    SubscriptionDetails details = new SubscriptionDetails();
    details.logExtension = logExtension;
    details.subscription = subscription;

    String id = uuidGenerator.getNextUUID();
    subscriptions.put(id, details);
    List<String> subscriptionIds = sessionSubscriptions.get(session);
    if (subscriptionIds == null) {
        subscriptionIds = new ArrayList<String>();
        sessionSubscriptions.put(session, subscriptionIds);
    }
    subscriptionIds.add(id);

    logSubscriptionStart(id, logExtension);

    return id;
}
 
Example #7
Source File: CougarProtocolTest.java    From cougar with Apache License 2.0 6 votes vote down vote up
public ExecutionVenueNioServer createServer(TlsNioConfig cfg) {
    ExecutionVenueNioServer server = new ExecutionVenueNioServer();
    server.setNioConfig(cfg);
    NioLogger sessionLogger = new NioLogger("ALL");
    TransportCommandProcessor<SocketTransportCommand> processor = new SocketTransportCommandProcessor();
    CougarObjectIOFactory objectIOFactory = new HessianObjectIOFactory(false);
    ExecutionVenueServerHandler serverHandler = new ExecutionVenueServerHandler(sessionLogger, processor, objectIOFactory) {
        @Override
        public void messageReceived(IoSession session, Object message) throws Exception {
            session.write(message);
        }
    };
    server.setServerHandler(serverHandler);
    server.setServerExecutor(Executors.newCachedThreadPool());
    server.setSocketAcceptorProcessors(1);
    server.setTransportRegistry(new TransportRegistryImpl());
    final IoSessionManager sessionManager = new IoSessionManager();
    server.setSessionManager(sessionManager);
    sessionManager.setMaxTimeToWaitForRequestCompletion(5000);
    sessionManager.setNioLogger(sessionLogger);
    return server;
}
 
Example #8
Source File: WelderDecoder.java    From camelinaction with Apache License 2.0 6 votes vote down vote up
protected boolean doDecode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception {
    if (in.remaining() >= PAYLOAD_SIZE) {
        byte[] buf = new byte[in.remaining()];
        in.get(buf);
        
        // first 7 bytes are the sensor ID, last is the status
        // and the result message will look something like
        // MachineID=2371748;Status=Good
        StringBuilder sb = new StringBuilder();
        sb.append("MachineID=")
        .append(new String(buf, 0, PAYLOAD_SIZE - 1)).append(";")
        .append("Status=");
        if (buf[PAYLOAD_SIZE - 1] == '1') {
            sb.append("Good");
        } else {
            sb.append("Failure");
        }
        out.write(sb.toString());
        return true;
    } else {
        return false;
    }
}
 
Example #9
Source File: RequestResponseManagerImplTest.java    From cougar with Apache License 2.0 6 votes vote down vote up
@Test
public void responseReceivedAfterTimeout() throws IOException, InterruptedException {
    IoSession session = mock(IoSession.class);
    NioLogger logger = new NioLogger("ALL");
    RequestResponseManagerImpl impl = new RequestResponseManagerImpl(session, logger, 1);
    assertEquals(0, impl.getOutstandingRequestCount());

    WaitableResponseHandler responseHandler = new WaitableResponseHandler();
    long correlationId =  impl.sendRequest(new byte[0], responseHandler);

    Thread.sleep(2); // 2ms > 1ms

    impl.checkForExpiredRequests();

    ResponseMessage message = new ResponseMessage(correlationId, new byte[0]);
    impl.messageReceived(session, message);
    // just want no exceptions
}
 
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: MinaServer.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public Channel getChannel(InetSocketAddress remoteAddress) {
    Set<IoSession> sessions = acceptor.getManagedSessions(getBindAddress());
    for (IoSession session : sessions) {
        if (session.getRemoteAddress().equals(remoteAddress)) {
            return MinaChannel.getOrAddChannel(session, getUrl(), this);
        }
    }
    return null;
}
 
Example #12
Source File: HeapState.java    From cougar with Apache License 2.0 5 votes vote down vote up
public Subscription addSubscription(ClientConnectedObjectManager ccom, IoSession session, long heapId, String subscriptionId) {
    ClientSubscription sub = new ClientSubscription(ccom, session, heapId, subscriptionId);
    ClientSubscription existing = subscriptions.putIfAbsent(subscriptionId, sub);
    if (existing != null) {
        return null;
    }
    return sub;
}
 
Example #13
Source File: PooledServerConnectedObjectManager.java    From cougar with Apache License 2.0 5 votes vote down vote up
public void terminateSubscription(IoSession session, String subscriptionId, Subscription.CloseReason reason) {
    sessionSubscriptions.get(session).remove(subscriptionId);
    try {
        SubscriptionDetails sub = subscriptions.remove(subscriptionId);
        if (reason != REQUESTED_BY_PUBLISHER) {
            sub.subscription.close(reason);
        }
    } catch (Exception e) {
        LOGGER.warn("Error trying to close subscription");
    }
}
 
Example #14
Source File: TestServerHandler.java    From cougar with Apache License 2.0 5 votes vote down vote up
public void messageReceived(IoSession session, Object msg) throws Exception {
	DataInputStream dis = new DataInputStream((InputStream) msg);//NOSONAR
	int x = dis.readInt();
	System.out.println("TestServerHandler got: " + x + ". Thread " + Thread.currentThread());

	System.out.println("TestServerHandler responding...");
	write(session, x + 1);
}
 
Example #15
Source File: MinaHandler.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@Override
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
    MinaChannel channel = MinaChannel.getOrAddChannel(session, url, handler);
    try {
        handler.caught(channel, cause);
    } finally {
        MinaChannel.removeChannelIfDisconnectd(session);
    }
}
 
Example #16
Source File: RequestResponseManagerImpl.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Override
public void sessionClosed(IoSession session) {
    broken = true;
    final LinkedList<WaitingResponseHandler> callbackList = new LinkedList<WaitingResponseHandler>(callbacks.values());
    callbacks.clear();

    for (WaitingResponseHandler handler : callbackList) {
        handler.handler.sessionClosed();
    }
    LOG.info("Notified "+callbackList.size() +" outstanding requests for session "+NioUtils.getSessionId(session));
}
 
Example #17
Source File: PooledServerConnectedObjectManager.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Override
public void terminateSubscription(IoSession session, TerminateSubscription payload) {
    Subscription.CloseReason reason = Subscription.CloseReason.REQUESTED_BY_PUBLISHER;
    try {
        reason = Subscription.CloseReason.valueOf(payload.getCloseReason());
    } catch (IllegalArgumentException iae) {
        // unrecognised reason
    }
    terminateSubscription(session, heapUris.get(payload.getHeapId()), payload.getSubscriptionId(), reason);
}
 
Example #18
Source File: MinaHandler.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@Override
public void sessionOpened(IoSession session) throws Exception {
    MinaChannel channel = MinaChannel.getOrAddChannel(session, url, handler);
    try {
        handler.connected(channel);
    } finally {
        MinaChannel.removeChannelIfDisconnectd(session);
    }
}
 
Example #19
Source File: SessionRecyclerTest.java    From cougar with Apache License 2.0 5 votes vote down vote up
private IoSession getSession(int id) {
    final IoSession ioSession = mock(IoSession.class);
    when(ioSession.isConnected()).thenReturn(true);
    when(ioSession.isClosing()).thenReturn(false);
    when(ioSession.containsAttribute(ProtocolMessage.ProtocolMessageType.SUSPEND.name())).thenReturn(false);
    when(ioSession.containsAttribute(ProtocolMessage.ProtocolMessageType.DISCONNECT.name())).thenReturn(false);
    return ioSession;
}
 
Example #20
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 #21
Source File: ClientConnectedObjectManagerTest.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Test
public void secondSubscriptionClosedByPublisher() throws Exception {
    IoSession session = new MyIoSession(String.valueOf(ioSessionId++));

    NewHeapSubscription newHeapSubscription = new NewHeapSubscription(1, "sub1", "secondSubscriptionClosedByPublisher");
    InvocationResponse response = new InvocationResponseImpl(newHeapSubscription);
    WaitingObserver observer = new WaitingObserver();
    subject.handleSubscriptionResponse(session, response, observer);

    HeapDelta initial = new HeapDelta(1, 0, createUpdateList(createInitial()));
    subject.applyDelta(session, initial);

    waitForAndAssertNotFault(observer);

    Subscription sub1 = getSubscriptionFrom(observer.getExecutionResult().getResult());
    assertNotNull(sub1);
    assertNull(sub1.getCloseReason());

    NewHeapSubscription newHeapSubscription2 = new NewHeapSubscription(1, "sub2");
    InvocationResponse response2 = new InvocationResponseImpl(newHeapSubscription2);
    WaitingObserver observer2 = new WaitingObserver();
    subject.handleSubscriptionResponse(session, response2, observer2);

    waitForAndAssertNotFault(observer2);

    Subscription sub2 = getSubscriptionFrom(observer2.getExecutionResult().getResult());
    assertNotNull(sub2);
    assertNull(sub2.getCloseReason());

    assertFalse(sub1.equals(sub2));

    subject.terminateSubscription(session, new TerminateSubscription(1, "sub2", Subscription.CloseReason.REQUESTED_BY_PUBLISHER.name()));

    assertNull(sub1.getCloseReason());
    assertEquals(Subscription.CloseReason.REQUESTED_BY_PUBLISHER, sub2.getCloseReason());
}
 
Example #22
Source File: MinaCodecAdapter.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public void encode(IoSession session, Object msg, ProtocolEncoderOutput out) throws Exception {
    ChannelBuffer buffer = ChannelBuffers.dynamicBuffer(1024);
    MinaChannel channel = MinaChannel.getOrAddChannel(session, url, handler);
    try {
    	codec.encode(channel, buffer, msg);
    } finally {
        MinaChannel.removeChannelIfDisconnectd(session);
    }
    out.write(ByteBuffer.wrap(buffer.toByteBuffer()));
    out.flush();
}
 
Example #23
Source File: CougarProtocolTest.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuspendMessagesAreSkippedForV1Sessions() {
    CougarProtocol protocol = CougarProtocol.getServerInstance(new NioLogger("NONE"), 5000, 5000, null, false, false);
    IoSession ioSession = newV1Session();
    protocol.suspendSession(ioSession);
    verify(ioSession, never()).write(isA(SuspendMessage.class));
}
 
Example #24
Source File: IoSessionManagerTest.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuspendAndDisconnectMessagesAreWrittenForV2Sessions() {
    final IoSession ioSession = newSession(V2);

    sessionManager.shutdownSessions(singleton(ioSession), cougarProtocol, serverHandler);

    verify(ioSession).write(isA(SuspendMessage.class));
    verify(ioSession).write(isA(DisconnectMessage.class));
}
 
Example #25
Source File: ClientConnectedObjectManager.java    From cougar with Apache License 2.0 5 votes vote down vote up
public void applyDelta(IoSession session, HeapDelta payload) {
    nioLogger.log(NioLogger.LoggingLevel.TRANSPORT, session, "Applying update for heap, heapId = %s, updateId = %s", payload.getHeapId(), payload.getUpdateId());
    ConnectedHeaps heaps = heapsByServer.get(NioUtils.getSessionId(session));
    // if we've got no record then we can't continue, and we can't really throw an exception, so just warn and ignore..
    if (heaps == null) {
        nioLogger.log(NioLogger.LoggingLevel.TRANSPORT, session, "Have no heaps registered for this client, address = %s", session.getRemoteAddress().toString());
        LOGGER.warn("Received a connected object update, yet have no record of any subscriptions. {address={},heapId={},updateId={}}", session.getRemoteAddress().toString(), payload.getHeapId(), payload.getUpdateId());
        return;
    }

    HeapState heapState = heaps.getHeapState(payload.getHeapId());
    if (heapState == null) {
        nioLogger.log(NioLogger.LoggingLevel.TRANSPORT, session, "Can't find this heap for this client, address = %s, heapId = %s", session.getRemoteAddress().toString(), payload.getHeapId());
        LOGGER.warn("Received a connected object update, yet have no record of a subscription for this heap. {address={},heapId={},updateId={}}", session.getRemoteAddress().toString(), payload.getHeapId(), payload.getUpdateId());
        return;
    }

    boolean containsInitialUpdate = (!payload.getUpdates().isEmpty() && (payload.getUpdates().get(0) instanceof InitialUpdate));
    if (containsInitialUpdate) {
        nioLogger.log(NioLogger.LoggingLevel.TRANSPORT, session, "Queueing initial update to local heap, heapUri = %s", heapState.getHeapUri());
    } else {
        nioLogger.log(NioLogger.LoggingLevel.TRANSPORT, session, "Queueing patch to local heap, heapUri = %s", heapState.getHeapUri());
    }

    heapState.queueUpdate(payload);
    heaps.queueUpdatedHeap(payload.getHeapId());
    sessionsWithUpdates.add(NioUtils.getSessionId(session));
}
 
Example #26
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 #27
Source File: MinaClient.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
@Override
protected Channel getChannel() {
    IoSession s = session;
    if (s == null || ! s.isConnected())
        return null;
    return MinaChannel.getOrAddChannel(s, getUrl(), this);
}
 
Example #28
Source File: MinaHandler.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
    MinaChannel channel = MinaChannel.getOrAddChannel(session, url, handler);
    try {
        handler.received(channel, message);
    } finally {
        MinaChannel.removeChannelIfDisconnectd(session);
    }
}
 
Example #29
Source File: SessionRecyclerTest.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
    sessionFactory = mock(IoSessionFactory.class);

    Field sessionsField = IoSessionFactory.class.getDeclaredField("sessions");
    sessionsField.setAccessible(true);
    Map<SocketAddress, IoSession> sessions = new HashMap<SocketAddress, IoSession>();
    final IoSession session1 = getSession(1);
    final IoSession session2 = getSession(2);
    final IoSession session3 = getSession(3);
    sessions.put(session1.getRemoteAddress(), session1);
    sessions.put(session2.getRemoteAddress(), session2);
    sessions.put(session3.getRemoteAddress(), session3);

    sessionsField.set(sessionFactory, sessions);
    when(sessionFactory.getSession()).thenCallRealMethod();
    when(sessionFactory.isAvailable(any(IoSession.class))).thenCallRealMethod();

    Field lockField = IoSessionFactory.class.getDeclaredField("lock");
    lockField.setAccessible(true);
    lockField.set(sessionFactory, new Object());

    NetworkAddressResolver resolver = mock(NetworkAddressResolver.class);
    when(resolver.resolve(HOST1)).thenReturn(asSet(HOST1_IP1, HOST1_IP2));
    when(resolver.resolve(HOST2)).thenReturn(asSet(HOST2_IP1, HOST2_IP2));
    when(resolver.resolve(HOST3)).thenReturn(asSet(HOST3_IP1, HOST3_IP2));
    hosts = "HOST1:9003,HOST2:9003,HOST3:9003";
    recycler = new SessionRecycler(sessionFactory, resolver, hosts, 5000);
}
 
Example #30
Source File: CougarProtocolTest.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuspendMessagesAreWrittenForV2Sessions() {
    CougarProtocol protocol = CougarProtocol.getServerInstance(new NioLogger("NONE"), 5000, 5000, null, false, false);
    IoSession ioSession = newV2Session();
    protocol.suspendSession(ioSession);
    verify(ioSession).write(isA(SuspendMessage.class));
}