org.apache.mina.core.session.IoSession Java Examples

The following examples show how to use org.apache.mina.core.session.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: BceUserStatusListHandler.java    From gameserver with Apache License 2.0 6 votes vote down vote up
@Override
public void messageProcess(IoSession session, Object message, SessionKey sessionKey)
		throws Exception {
	if ( logger.isDebugEnabled() ) {
		logger.debug("->BceUserStatusList");
	}
	
	XinqiMessage request = (XinqiMessage)message;
	User user = GameContext.getInstance().findLocalUserBySessionKey(sessionKey);
	
	BceUserStatusList statusList = (BceUserStatusList)request.payload;
	int limit = statusList.getLimit();
	List<String> userActions = UserActionManager.getInstance().getUserActions(limit);
	BseUserStatusList.Builder builder = BseUserStatusList.newBuilder();
	if ( userActions != null ) {
		for ( String userAction : userActions ) {
			builder.addStatuslist(userAction);
		}
	}
	GameContext.getInstance().writeResponse(sessionKey, builder.build());
}
 
Example #2
Source File: AbstractMINAService.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
@Override
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
    logger.error("Session exception: {}", session, cause);

    String stackTrace = ExceptionUtils.getStackTrace(cause);
    IMessage message = ServiceUtil.createErrorMessage(stackTrace, "Unknown", getName(), serviceInfo, messageFactory);

    try {
        storage.storeMessage(message);
    } catch(Exception e) {
        logger.error("Failed to store error message", e) ;
    }

    MINASession minaSession = getSession();

    if(minaSession != null) {
        getServiceHandler().exceptionCaught(minaSession, cause);
    }
}
 
Example #3
Source File: BceLeaveMessageHandler.java    From gameserver with Apache License 2.0 6 votes vote down vote up
@Override
public void messageProcess(IoSession session, Object message, SessionKey sessionKey)
		throws Exception {
	if ( log.isDebugEnabled() ) {
		log.debug("->BceLeaveMessage");
	}
	
	XinqiMessage request = (XinqiMessage)message;
	XinqiMessage response = new XinqiMessage();
	XinqiBseLeaveMessage.BseLeaveMessage.Builder builder = XinqiBseLeaveMessage.BseLeaveMessage.newBuilder();
	response.payload = builder.build();
	//TODO BEGIN add logic here.
	//builder.setUid(((XinqiBceLeaveMessage.BceLeaveMessage)request.payload).getUid());
	//END
	session.write(response);
	System.out.println("BceLeaveMessage: " + response);
}
 
Example #4
Source File: BcePickGoldHandler.java    From gameserver with Apache License 2.0 6 votes vote down vote up
@Override
public void messageProcess(IoSession session, Object message, SessionKey sessionKey)
		throws Exception {
	if ( log.isDebugEnabled() ) {
		log.debug("->BcePickGold");
	}
	
	XinqiMessage request = (XinqiMessage)message;
	XinqiMessage response = new XinqiMessage();
	XinqiBsePickGold.BsePickGold.Builder builder = XinqiBsePickGold.BsePickGold.newBuilder();
	response.payload = builder.build();
	//TODO BEGIN add logic here.
	//builder.setUid(((XinqiBcePickGold.BcePickGold)request.payload).getUid());
	//END
	session.write(response);
	System.out.println("BcePickGold: " + response);
}
 
Example #5
Source File: SslFilter.java    From jane with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * An extended toString() method for sessions.
 * If the SSL handshake is not yet completed, we will print (ssl) in small caps.
 * Once it's completed, we will use SSL capitalized.
 */
public static String getSessionInfo(IoSession session) {
	StringBuilder sb = new StringBuilder();
	sb.append(session.getService() instanceof IoAcceptor ? "session server" : "session client");
	sb.append('[').append(session.getId()).append(']');

	SslHandler sslHandler = (SslHandler)session.getAttribute(SSL_HANDLER);
	if (sslHandler == null)
		sb.append("(no sslEngine)");
	else if (sslHandler.isOutboundDone())
		sb.append("(done)");
	else
		sb.append(sslHandler.isHandshakeComplete() ? "(SSL)" : "(SSL...)");

	return sb.toString();
}
 
Example #6
Source File: BceForgeHandler.java    From gameserver with Apache License 2.0 6 votes vote down vote up
@Override
public void messageProcess(IoSession session, Object message, SessionKey sessionKey)
		throws Exception {
	if ( log.isDebugEnabled() ) {
		log.debug("->BceForge");
	}
	
	XinqiMessage request = (XinqiMessage)message;
	BceForge forge = (BceForge)request.payload;
	int equipPew = forge.getEquipPew();
	int[] pews = new int[forge.getOtherPewsCount()];
	for ( int i=0; i<pews.length; i++ ) {
		pews[i] = forge.getOtherPews(i);
	}
	
	//The User object should not be null because GameHandler is checking it.
	User user = GameContext.getInstance().findLocalUserBySessionKey(sessionKey);
	GameContext.getInstance().getCraftManager().forgeEquip(user, equipPew, pews);
}
 
Example #7
Source File: ProtocolCodecFilter.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void sessionClosed(NextFilter nextFilter, IoSession session) throws Exception {
    // Call finishDecode() first when a connection is closed.
    ProtocolDecoder decoder = factory.getDecoder(session);
    ProtocolDecoderOutput decoderOut = getDecoderOut(session, nextFilter);

    try {
        decoder.finishDecode(session, decoderOut);
    } catch (Throwable t) {
        ProtocolDecoderException pde;
        if (t instanceof ProtocolDecoderException) {
            pde = (ProtocolDecoderException) t;
        } else {
            pde = new ProtocolDecoderException(t);
        }
        throw pde;
    } finally {
        // Dispose everything
        disposeCodec(session);
        decoderOut.flush(nextFilter, session);
    }

    // Call the next filter
    nextFilter.sessionClosed(session);
}
 
Example #8
Source File: BceLeaveHallHandler.java    From gameserver with Apache License 2.0 6 votes vote down vote up
@Override
public void messageProcess(IoSession session, Object message, SessionKey sessionKey)
		throws Exception {
	if ( log.isDebugEnabled() ) {
		log.debug("->BceLeaveHall");
	}
	
	XinqiMessage request = (XinqiMessage)message;
	XinqiMessage response = new XinqiMessage();
	XinqiBseLeaveHall.BseLeaveHall.Builder builder = XinqiBseLeaveHall.BseLeaveHall.newBuilder();
	response.payload = builder.build();
	//TODO BEGIN add logic here.
	//builder.setUid(((XinqiBceLeaveHall.BceLeaveHall)request.payload).getUid());
	//END
	session.write(response);
	System.out.println("BceLeaveHall: " + response);
}
 
Example #9
Source File: LdapProtocolDecoder.java    From directory-ldap-api with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void decode( IoSession session, IoBuffer in, ProtocolDecoderOutput out ) throws Exception
{
    @SuppressWarnings("unchecked")
    LdapMessageContainer<AbstractMessage> messageContainer =
        ( LdapMessageContainer<AbstractMessage> )
        session.getAttribute( LdapDecoder.MESSAGE_CONTAINER_ATTR );

    if ( session.containsAttribute( LdapDecoder.MAX_PDU_SIZE_ATTR ) )
    {
        int maxPDUSize = ( Integer ) session.getAttribute( LdapDecoder.MAX_PDU_SIZE_ATTR );

        messageContainer.setMaxPDUSize( maxPDUSize );
    }

    List<Message> decodedMessages = new ArrayList<>();
    ByteBuffer buf = in.buf();

    decode( buf, messageContainer, decodedMessages );

    for ( Message message : decodedMessages )
    {
        out.write( message );
    }
}
 
Example #10
Source File: MinaClientHandler.java    From grain with MIT License 5 votes vote down vote up
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
	super.messageReceived(session, message);
	if (MinaConfig.log != null) {
		MinaConfig.log.info("minaclient messageReceived");
	}
	// 派发tcp
	TcpManager.dispatchTcp((TcpPacket) message);
}
 
Example #11
Source File: NTGClient.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
@Override
public final void sessionIdle(IoSession session, IdleStatus status) throws Exception {
       super.sessionIdle(session, status);
       taskExecutor.addTask(() -> {
           try {
               sendHeartbeat();
           } catch(InterruptedException e) {
               throw new ServiceException("Failed to send heartbeat", e);
           }
       });
}
 
Example #12
Source File: SessionManagerTest.java    From gameserver with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("static-access")
	@Test
	public void testDeregisterSessionWithTimeout() throws Exception {
		GlobalConfig.getInstance().overrideProperty("runtime.local_messageserver", "localhost:12345");
		GlobalConfig.getInstance().overrideProperty(GlobalConfigKey.session_timeout_seconds, "1");
		
		Jedis jedis = JedisFactory.getJedis();
		
		SessionManager manager = new SessionManager();
		UserId userId = new UserId("test-001");
		User user = UserManager.getInstance().createDefaultUser();
		user.set_id(userId);
		
		IoSession session = createNiceMock(IoSession.class);
//		expect(session.getAttribute(anyObject())).andReturn(message.getSessionkey()).times(1);
		expect(session.removeAttribute(anyObject())).andReturn(null).times(1);
		
		replay(session);
		
		SessionKey createdKey = manager.registerSession(session, user);
		manager.deregisterSession(session, user);
		
		assertEquals(null, (session.getAttribute(Constant.SESSION_KEY)));
		
		String localSessionPrefix = manager.getLocalSessionPrefix();
		
		assertTrue(jedis.exists(createdKey.toString()));
		assertEquals(new Long(1), jedis.ttl(createdKey.toString()));
		assertEquals(new Long(1), jedis.ttl(userId.toString()));
		assertEquals(new Long(1), jedis.ttl(localSessionPrefix+createdKey.toString()));
	
		Thread.currentThread().sleep(2000);

		assertTrue(!jedis.exists(createdKey.toString()));
		assertEquals(null, jedis.get(userId.toString()));
		assertEquals(null, jedis.get(localSessionPrefix+createdKey.toString()));
		
		verify(session);
	
	}
 
Example #13
Source File: TCPIPServer.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
@Override
public void sessionOpened(IoSession session) throws Exception {
    handler.sessionOpened(sessionMap.get(session));

    storeSessionEventMessage(session, "connection opened!");

    logger.info("sessionOpened: {} {} {}",
            session, session.getClass().getCanonicalName(), session.hashCode());
}
 
Example #14
Source File: GameContext.java    From gameserver with Apache License 2.0 5 votes vote down vote up
/**
 * Find the session key in current JVM server.
 * @param sessionKey
 * @return
 */
public IoSession findLocalUserIoSession(SessionKey sessionKey) {
	User user = loginUserMap.get(sessionKey);
	if ( user != null ) {
		return user.getSession();
	}
	return null;
}
 
Example #15
Source File: SslFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void initiateHandshake(NextFilter nextFilter, IoSession session) throws SSLException {
    LOGGER.debug("{} : Starting the first handshake", getSessionInfo(session));
    SslHandler handler = getSslSessionHandler(session);

    synchronized (handler) {
        handler.handshake(nextFilter);
    }

    handler.flushScheduledEvents();
}
 
Example #16
Source File: MinaCodecAdapter.java    From JobX with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(IoSession session, Object msg, ProtocolEncoderOutput out) throws Exception {
    if (type.isInstance(msg)) {
        byte[] data =  serializer.serialize(msg);
        IoBuffer buffer = IoBuffer.allocate(100);
        buffer.setAutoExpand(true);
        buffer.setAutoShrink(true);
        buffer.putInt(data.length);
        buffer.put(data);
        buffer.flip();
        session.write(buffer);
    }
}
 
Example #17
Source File: AbstractPollingConnectionlessIoAcceptor.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void processReadySessions( Set<SelectionKey> handles )
{
    Iterator<SelectionKey> iterator = handles.iterator();

    while ( iterator.hasNext() )
    {
        SelectionKey key = iterator.next();
        H handle = ( H ) key.channel();
        iterator.remove();

        try
        {
            if ( ( key != null ) && key.isValid() && key.isReadable() )
            {
                readHandle( handle );
            }

            if ( ( key != null ) && key.isValid() && key.isWritable() )
            {
                for ( IoSession session : getManagedSessions().values() )
                {
                    scheduleFlush( ( S ) session );
                }
            }
        }
        catch ( Throwable t )
        {
            ExceptionMonitor.getInstance().exceptionCaught( t );
        }
    }
}
 
Example #18
Source File: BlacklistFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void sessionOpened(NextFilter nextFilter, IoSession session) throws Exception {
    if (!isBlocked(session)) {
        // forward if not blocked
        nextFilter.sessionOpened(session);
    } else {
        blockSession(session);
    }
}
 
Example #19
Source File: MessageUtil.java    From CXTouch with GNU General Public License v3.0 5 votes vote down vote up
public static void sendMessage(IoSession session, Message message) throws MessageException {
    if (session == null || !session.isConnected()) {
        throw new MessageException("Connection is invalid!");
    }

    IoBuffer buffer = message.getBinary();
    buffer.flip();
    int size = buffer.remaining();
    WriteFuture future = session.write(buffer);

}
 
Example #20
Source File: AccountManager.java    From gameserver with Apache License 2.0 5 votes vote down vote up
/**
 * Disable the role 
 * @param session
 * @param user
 * @param serverId
 */
public void disableGameRole(final IoSession session, final User user, final String serverId) {
	Account account = (Account)session.getAttribute(IOSESSION_ACCOUNT);
	String userid = user.get_id().toString();
	String roleName = user.getRoleName();

	if ( account != null ) {
		ArrayList<ServerRoleList> serverRoles = account.getServerRoles();
		UserId deleteUserId = null;
		LOOP:
		for ( ServerRoleList roleList : serverRoles ) {
			if ( serverId.equals(roleList.getServerId()) ) {
				ArrayList<String> userIds = roleList.getUserIds();
				ArrayList<String> roleNames = roleList.getRoleNames();
				for ( int i=0; i<userIds.size(); i++ ) {
					String rn = userIds.get(i);
					if ( userid.equals(rn) ) {
						deleteUserId = UserId.fromString(userid);
						break LOOP;
					}
				}
			}
		}
		if ( deleteUserId != null ) {
			if ( deleteUserId.equals(user.get_id()) ) {
				user.setLoginStatus(UserLoginStatus.HIDE);
				UserManager.getInstance().saveUser(user, false);
			} else {
				logger.warn("Failed to disable the user {} because id not matched.");
			}
		}
	} else {
		logger.warn("Not found the account");
	}
	BseDeleteRole.Builder builder = BseDeleteRole.newBuilder();
	builder.setErrorcode(0);
	builder.setDesc(Text.text("deleterole.success", roleName));
	GameContext.getInstance().writeResponse(session, builder.build(), null);
	StatClient.getIntance().sendDataToStatServer(user, StatAction.DeleteRole, roleName, serverId, true);	
}
 
Example #21
Source File: UDPDestination.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void processStreamIo(IoSession session, InputStream in, OutputStream out) {
    final MessageImpl m = new MessageImpl();
    final Exchange exchange = new ExchangeImpl();
    exchange.setDestination(UDPDestination.this);
    m.setDestination(UDPDestination.this);
    exchange.setInMessage(m);
    m.setContent(InputStream.class, in);
    out = new UDPDestinationOutputStream(out);
    m.put(OutputStream.class, out);
    queue.execute(() -> getMessageObserver().onMessage(m));
}
 
Example #22
Source File: StreamIoHandler.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Handles read timeout.
 */
@Override
public void sessionIdle(IoSession session, IdleStatus status) {
    if (status == IdleStatus.READER_IDLE) {
        throw new StreamIoException(new SocketTimeoutException("Read timeout"));
    }
}
 
Example #23
Source File: ClientConnectionHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * In addition to the functionality provided by the parent class, this
 * method will send XMPP ping requests to the remote entity on every first
 * invocation of this method (which will occur after a period of half the
 * allowed connection idle time has passed, without any IO).
 * 
 * XMPP entities must respond with either an IQ result or an IQ error
 * (feature-unavailable) stanza upon receiving the XMPP ping stanza. Both
 * responses will be received by Openfire and will cause the connection idle
 * count to be reset.
 * 
 * Entities that do not respond to the IQ Ping stanzas can be considered
 * dead, and their connection will be closed by the parent class
 * implementation on the second invocation of this method.
 * 
 * Note that whitespace pings that are sent by XMPP entities will also cause
 * the connection idle count to be reset.
 * 
 * @see ConnectionHandler#sessionIdle(IoSession, IdleStatus)
 */
@Override
public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
    super.sessionIdle(session, status);
    
    final boolean doPing = ConnectionSettings.Client.KEEP_ALIVE_PING_PROPERTY.getValue();
    if (doPing && session.getIdleCount(status) == 1) {
        final ClientStanzaHandler handler = (ClientStanzaHandler) session.getAttribute(HANDLER);
        final JID entity = handler.getAddress();
        
        if (entity != null) {
            // Ping the connection to see if it is alive.
            final IQ pingRequest = new IQ(Type.get);
            pingRequest.setChildElement("ping",
                    IQPingHandler.NAMESPACE);
            pingRequest.setFrom( XMPPServer.getInstance().getServerInfo().getXMPPDomain() );
            pingRequest.setTo(entity); 
            
            // Get the connection for this session
            final Connection connection = (Connection) session.getAttribute(CONNECTION);

            if (Log.isDebugEnabled()) {
                Log.debug("ConnectionHandler: Pinging connection that has been idle: " + connection);
            }

            // OF-1497: Ensure that data sent to the client is processed through LocalClientSession, to avoid
            // synchronisation issues with stanza counts related to Stream Management (XEP-0198)!
            LocalClientSession ofSession = (LocalClientSession) SessionManager.getInstance().getSession( entity );
            if (ofSession == null) {
                Log.warn( "Trying to ping a MINA connection that's idle, but has no corresponding Openfire session. MINA Connection: " + connection );
            } else {
                ofSession.deliver( pingRequest );
            }
        }
    }
}
 
Example #24
Source File: ModbusTcpEncoder.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void encode ( final IoSession session, final Object message, final ProtocolEncoderOutput out ) throws Exception
{
    logger.debug ( "Encoding: {}", message );
    final Pdu request = (Pdu)message;

    final IoBuffer buffer = IoBuffer.allocate ( request.getData ().remaining () + 7 );
    buffer.setAutoExpand ( true );

    final IoBuffer pdu = request.getData ();

    // put transaction identifier
    buffer.putUnsignedShort ( request.getTransactionId () );
    // put modbus protocol identifier (always 0)
    buffer.putUnsignedShort ( 0 );
    // put length, including slave id
    buffer.putUnsignedShort ( request.getData ().remaining () + 1 );
    // put slave id
    buffer.put ( request.getUnitIdentifier () );
    // put data
    buffer.put ( pdu );

    buffer.flip ();

    logger.trace ( "Encoded to: {}", buffer );

    out.write ( buffer );
}
 
Example #25
Source File: DistributedlockServerHandler.java    From grain with MIT License 5 votes vote down vote up
@Override
public void sessionClosed(IoSession session) throws Exception {
	super.sessionClosed(session);
	if (MinaConfig.log != null) {
		MinaConfig.log.warn("minaserver sessionClosed");
	}
	ThreadMsgManager.dispatchThreadMsg(TcpMsg.MINA_CLIENT_DISCONNECT, null, session);
}
 
Example #26
Source File: ServerProtocolTCPDecoder.java    From seed with Apache License 2.0 5 votes vote down vote up
@Override
public MessageDecoderResult decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    byte[] message = new byte[in.limit()];
    in.get(message);
    String fullMessage = StringUtils.toEncodedString(message, Charset.forName(SeedConstants.DEFAULT_CHARSET));
    Token token = new Token();
    token.setBusiCharset(SeedConstants.DEFAULT_CHARSET);
    token.setBusiType(Token.BUSI_TYPE_TCP);
    token.setBusiCode(fullMessage.substring(6, 11));
    token.setBusiMessage(fullMessage);
    token.setFullMessage(fullMessage);
    out.write(token);
    return MessageDecoderResult.OK;
}
 
Example #27
Source File: TestMsgService.java    From grain with MIT License 5 votes vote down vote up
public void onClientConnected(MsgPacket msgPacket) {
	IoSession session = (IoSession) msgPacket.getOtherData();
	System.out.println("接到消息:" + msgPacket.getMsgOpCode());
	RPCTestS.Builder builder = RPCTestS.newBuilder();
	builder.setName("RPC你好啊");
	TcpPacket pt = new TcpPacket(TestTCode.TEST_RPC_SERVER, builder.build());

	TcpPacket ptReturn = WaitLockManager.lock(session, pt);
	RPCTestC rpcTestC = (RPCTestC) ptReturn.getData();
	System.out.println("接到RPC消息:" + rpcTestC.getName());

}
 
Example #28
Source File: PressureClientHandler.java    From game-server with MIT License 5 votes vote down vote up
@Override
	public void sessionCreated(IoSession session) throws Exception {
		super.sessionCreated(session);
//		IoFilter filter = session.getFilterChain().get(SslFilter.class);
//		if(filter!=null){
//			SslFilter sslFilter=(SslFilter)filter;
//			sslFilter.setUseClientMode(true);
//			sslFilter.startSsl(session);
//			sslFilter.initiateHandshake(session);
//		}
	}
 
Example #29
Source File: TestITCHCodecPositive.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
/**
 * Try to decode AddOrderOneByteLength from byte[] and print result message into console.
 */
@Ignore@Test
public void testDecodeMessageAddOrderOneByteLength(){
       ITCHCodec codec = (ITCHCodec) getMessageHelper().getCodec(serviceContext);
       int[] array = {0x2E, 0x00, 0x01, 0x31, 0x10, 0x05, 0x00, 0x00, 0x2E, 0x41, 0xE0, 0x98, 0xC3, 0x22, 0x0E, 0x00,
        0x00, 0x40, 0xC4, 0xD4, 0x57, 0x01, 0x42, 0xE8, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3D,
        0xE6, 0x46, 0x00, 0x00, 0x00, 0x00, 0x4E, 0x72, 0x53, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
       byte[] b = new byte[array.length];
	for (int i=0; i<array.length; i++)
	{
		b[i] = (byte) array[i];
	}

	IoBuffer toDecode = IoBuffer.wrap( b );
	toDecode.order(ByteOrder.LITTLE_ENDIAN);
	toDecode.position(0);

	IoSession decodeSession = new DummySession();
	MockProtocolDecoderOutput decoderOutput = new MockProtocolDecoderOutput();
	try{
		boolean decodableResult = codec.doDecode( decodeSession, toDecode, decoderOutput );
		System.out.println((IMessage) decoderOutput.getMessageQueue().element());
		Assert.assertTrue( "Decoding error.", decodableResult);
	}catch(Exception e){
		logger.error(e.getMessage(),e);
		Assert.fail(e.getMessage());
	}
}
 
Example #30
Source File: DefaultConnectFuture.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public IoSession getSession() {
	Object v = getValue();
	if (v instanceof IoSession)
		return (IoSession)v;
	if (v instanceof RuntimeException)
		throw (RuntimeException)v;
	if (v instanceof Error)
		throw (Error)v;
	if (v instanceof Throwable)
		throw new RuntimeException("failed to get the session", (Throwable)v);
	return null;
}