Java Code Examples for org.apache.mina.core.session.IoSession#getAttribute()

The following examples show how to use org.apache.mina.core.session.IoSession#getAttribute() . 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: ModbusRtuDecoder.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public synchronized void decode ( final IoSession session, final IoBuffer in, final ProtocolDecoderOutput out ) throws Exception
{
    IoBuffer currentFrame = (IoBuffer)session.getAttribute ( SESSION_KEY_CURRENT_FRAME );
    if ( currentFrame == null )
    {
        currentFrame = IoBuffer.allocate ( Constants.MAX_PDU_SIZE + Constants.RTU_HEADER_SIZE );
        session.setAttribute ( SESSION_KEY_CURRENT_FRAME, currentFrame );
    }
    logger.trace ( "decode () current frame = {} data = {}", currentFrame.toString (), currentFrame.getHexDump () );
    logger.trace ( "decode () new     frame = {} data = {}", in.toString (), in.getHexDump () );

    final int expectedSize = currentFrame.position () + in.remaining ();
    if ( expectedSize > MAX_SIZE + 1 )
    {
        throw new ModbusProtocolError ( String.format ( "received size (%s) exceeds max size (%s)", expectedSize, MAX_SIZE ) );
    }
    currentFrame.put ( in );

    tick ( session, out );
}
 
Example 2
Source File: GameHandler.java    From gameserver with Apache License 2.0 6 votes vote down vote up
@Override
public void sessionIdle(IoSession session, IdleStatus status)
		throws Exception {
	if ( StatClient.getIntance().isStatEnabled() ) {
		SessionKey userSessionKey = (SessionKey)session.getAttribute(Constant.SESSION_KEY);
		if ( userSessionKey != null ) {
			User user = GameContext.getInstance().findLocalUserBySessionKey(userSessionKey);
			if ( user != null ) {
				GameContext.getInstance().deregisterUserBySessionKey(userSessionKey);
				logger.debug("User {} session is idle too much time. Close it.", user.getRoleName());
				
				StatClient.getIntance().sendDataToStatServer(user, StatAction.LogoutIdle);
			}
		}
	}
	try {
		session.close(false);
		//do cleaning
	} catch (Throwable e) {
	}
}
 
Example 3
Source File: StatisticsFilter.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
private StatisticsImpl getStats ( final IoSession session )
{
    final Object o = session.getAttribute ( StatisticsFilter.STATS_KEY );
    if ( o instanceof StatisticsImpl )
    {
        final StatisticsImpl stats = (StatisticsImpl)o;
        if ( this.statsMapper.add ( stats ) )
        {
            init ( stats );
        }
        return stats;
    }
    else
    {
        return null;
    }
}
 
Example 4
Source File: RedisProtocolDecoder.java    From Redis-Synyed with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
	RedisProtocolParser parser = (RedisProtocolParser) session.getAttribute(REDIS_PROTOCOL_PARSER);
	// 将接收到的数据通过解析器解析为Redis数据包对象
	parser.read(in.buf());

	// 获取解析器解析出的数据包
	RedisPacket[] redisPackets = parser.getPackets();
	if (redisPackets != null) {
		for (RedisPacket redisPacket : redisPackets) {
			out.write(redisPacket);
		}
	}

	// 以是否读取完数据为判断符
	return !in.hasRemaining();
}
 
Example 5
Source File: CompressionFilter.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {
    if (!compressInbound || !(message instanceof IoBuffer)) {
        nextFilter.messageReceived(session, message);
        return;
    }

    Zlib inflater = (Zlib) session.getAttribute(INFLATER);
    if (inflater == null) {
        throw new IllegalStateException();
    }

    IoBuffer inBuffer = (IoBuffer) message;
    IoBuffer outBuffer = inflater.inflate(inBuffer);
    nextFilter.messageReceived(session, outBuffer);
}
 
Example 6
Source File: CompressionFilter.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected Object doFilterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest)
        throws IOException {
    if (!compressOutbound) {
        return null;
    }

    if (session.containsAttribute(DISABLE_COMPRESSION_ONCE)) {
        // Remove the marker attribute because it is temporary.
        session.removeAttribute(DISABLE_COMPRESSION_ONCE);
        return null;
    }

    Zlib deflater = (Zlib) session.getAttribute(DEFLATER);
    if (deflater == null) {
        throw new IllegalStateException();
    }

    IoBuffer inBuffer = (IoBuffer) writeRequest.getMessage();
    if (!inBuffer.hasRemaining()) {
        // Ignore empty buffers
        return null;
    } else {
        return deflater.deflate(inBuffer);
    }
}
 
Example 7
Source File: SslFilter.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void filterClose(final NextFilter nextFilter, final IoSession session) throws Exception {
	SslHandler sslHandler = (SslHandler)session.getAttribute(SSL_HANDLER);
	if (sslHandler == null) {
		// The connection might already have closed, or SSL might have not started yet.
		nextFilter.filterClose();
		return;
	}

	WriteFuture future = null;
	try {
		synchronized (sslHandler) {
			if (isSslStarted(session)) {
				future = initiateClosure(nextFilter, session, true);
				future.addListener(__ -> nextFilter.filterClose());
			}
		}

		sslHandler.flushScheduledEvents();
	} catch (SSLException se) {
		sslHandler.release();
		throw se;
	} finally {
		if (future == null)
			nextFilter.filterClose();
	}
}
 
Example 8
Source File: ConnectionHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void sessionClosed(IoSession session) throws Exception {
    final Connection connection = (Connection) session.getAttribute(CONNECTION);
    if ( connection != null ) {
        connection.close();
    }
}
 
Example 9
Source File: MessageChannelCodecFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private CharsetEncoder getCharsetEncoder ( final IoSession session )
{
    if ( session.containsAttribute ( "charsetEncoder" ) )
    {
        return (CharsetEncoder)session.getAttribute ( "charsetEncoder" );
    }

    final CharsetEncoder encoder = Charset.forName ( "UTF-8" ).newEncoder ();
    session.setAttribute ( "charsetEncoder", encoder );
    return encoder;
}
 
Example 10
Source File: WebSocketHandler.java    From red5-websocket with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
    if (log.isTraceEnabled()) {
        log.trace("Message received (session: {}) {}", session.getId(), message);
    }
    if (message instanceof WSMessage) {
        WebSocketConnection conn = (WebSocketConnection) session.getAttribute(Constants.CONNECTION);
        if (conn != null) {
            conn.receive((WSMessage) message);
        }
    } else {
        log.trace("Non-WSMessage received {}", message);
    }
}
 
Example 11
Source File: SslFilter.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @param session the session we want to check
 * @return <tt>true</tt> if and only if the conditions for {@link #isSslStarted(IoSession)} are met, and the handhake has completed.
 */
public static boolean isSecured(IoSession session) {
	SslHandler sslHandler = (SslHandler)session.getAttribute(SSL_HANDLER);
	if (sslHandler == null)
		return false;

	synchronized (sslHandler) {
		return !sslHandler.isOutboundDone() && sslHandler.isHandshakeComplete();
	}
}
 
Example 12
Source File: TimedEndDecoder.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Get the context for a session
 * 
 * @param session
 *            the session
 * @return the context
 */
private Context getTimedContext ( final IoSession session, final boolean create )
{
    Context ctx = (Context)session.getAttribute ( CONTEXT );
    if ( ctx == null && create )
    {
        ctx = new Context ( this, this.timeout, session );
        registerContext ( ctx );
        session.setAttribute ( CONTEXT, ctx );
    }
    return ctx;
}
 
Example 13
Source File: DefaultCoreSession.java    From MyVirtualDirectory with Apache License 2.0 5 votes vote down vote up
/**
 * Stores the IoSession into the CoreSession. This is only useful when the server is not embedded.
 * 
 * @param ioSession The IoSession for this CoreSession
 */
public void setIoSession( IoSession ioSession )
{
    this.ioSession = ioSession;
    HashMap<Object,Object> lsession = (HashMap<Object, Object>) ioSession.getAttribute("MYVD_USER_SESSION");
    if (lsession != null) {
    	this.userSession = lsession;
    }
}
 
Example 14
Source File: MaplePacketDecoder.java    From HeavenMS with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    final MapleClient client = (MapleClient) session.getAttribute(MapleClient.CLIENT_KEY);
    if(client == null) {
        MapleSessionCoordinator.getInstance().closeSession(session, true);
        return false;
    }
    
    DecoderState decoderState = (DecoderState) session.getAttribute(DECODER_STATE_KEY);
    if (decoderState == null) {
        decoderState = new DecoderState();
        session.setAttribute(DECODER_STATE_KEY, decoderState);
    }
    
    MapleAESOFB rcvdCrypto = client.getReceiveCrypto();
    if (in.remaining() >= 4 && decoderState.packetlength == -1) {
        int packetHeader = in.getInt();
        if (!rcvdCrypto.checkPacket(packetHeader)) {
            MapleSessionCoordinator.getInstance().closeSession(session, true);
            return false;
        }
        decoderState.packetlength = MapleAESOFB.getPacketLength(packetHeader);
    } else if (in.remaining() < 4 && decoderState.packetlength == -1) {
        return false;
    }
    if (in.remaining() >= decoderState.packetlength) {
        byte decryptedPacket[] = new byte[decoderState.packetlength];
        in.get(decryptedPacket, 0, decoderState.packetlength);
        decoderState.packetlength = -1;
        rcvdCrypto.crypt(decryptedPacket);
        MapleCustomEncryption.decryptData(decryptedPacket);
        out.write(decryptedPacket);
        if (YamlConfig.config.server.USE_DEBUG_SHOW_PACKET){ // Atoot's idea: packet traffic log, applied using auto-identation thanks to lrenex
            int packetLen = decryptedPacket.length;
            int pHeader = readFirstShort(decryptedPacket);
            String pHeaderStr = Integer.toHexString(pHeader).toUpperCase();
            String op = lookupSend(pHeader);
            String Send = "ClientSend:" + op + " [" + pHeaderStr + "] (" + packetLen + ")\r\n";
            if (packetLen <= 3000) {
                String SendTo = Send + HexTool.toString(decryptedPacket) + "\r\n" + HexTool.toStringFromAscii(decryptedPacket);
                System.out.println(SendTo);
                if (op == null) {
                    System.out.println("UnknownPacket:" + SendTo);
                }
            } else {
                FilePrinter.print(FilePrinter.PACKET_STREAM + MapleSessionCoordinator.getSessionRemoteAddress(session) + ".txt", HexTool.toString(new byte[]{decryptedPacket[0], decryptedPacket[1]}) + "...");
            }
        }
        return true;
    }
    return false;
}
 
Example 15
Source File: MaplePacketEncoder.java    From HeavenMS with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
    public void encode(final IoSession session, final Object message, final ProtocolEncoderOutput out) throws Exception {
        final MapleClient client = (MapleClient) session.getAttribute(MapleClient.CLIENT_KEY);

        try {
            if (client.tryacquireEncoder()) {
                try {
                    final MapleAESOFB send_crypto = client.getSendCrypto();
                    final byte[] input = (byte[]) message;
                    if (YamlConfig.config.server.USE_DEBUG_SHOW_PACKET) {
                        int packetLen = input.length;
                        int pHeader = readFirstShort(input);
                        String pHeaderStr = Integer.toHexString(pHeader).toUpperCase();
                        String op = lookupRecv(pHeader);
                        String Recv = "ServerSend:" + op + " [" + pHeaderStr + "] (" + packetLen + ")\r\n";
                        if (packetLen <= 50000) {
                            String RecvTo = Recv + HexTool.toString(input) + "\r\n" + HexTool.toStringFromAscii(input);
                            System.out.println(RecvTo);
                            if (op == null) {
                                System.out.println("UnknownPacket:" + RecvTo);
                            }
                        } else {
                            FilePrinter.print(FilePrinter.PACKET_STREAM + MapleSessionCoordinator.getSessionRemoteAddress(session) + ".txt", HexTool.toString(new byte[]{input[0], input[1]}) + " ...");
                        }
                    }

                    final byte[] unencrypted = new byte[input.length];
                    System.arraycopy(input, 0, unencrypted, 0, input.length);
                    final byte[] ret = new byte[unencrypted.length + 4];
                    final byte[] header = send_crypto.getPacketHeader(unencrypted.length);
                    MapleCustomEncryption.encryptData(unencrypted);

                    send_crypto.crypt(unencrypted);
                    System.arraycopy(header, 0, ret, 0, 4);
                    System.arraycopy(unencrypted, 0, ret, 4, unencrypted.length);

                    out.write(IoBuffer.wrap(ret));
                } finally {
                    client.unlockEncoder();
                }
            }
//            System.arraycopy(unencrypted, 0, ret, 4, unencrypted.length);
//            out.write(ByteBuffer.wrap(ret));
        } catch (NullPointerException npe) {
            out.write(IoBuffer.wrap(((byte[]) message)));
        }
    }
 
Example 16
Source File: WebSocketDecoder.java    From game-server with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
    @Override
    protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {        
        IoBuffer resultBuffer;
        if(!session.containsAttribute(WebSocketUtils.SessionAttribute)){
            // first message on a new connection. see if its from a websocket or a 
            // native socket.
            if(tryWebSockeHandShake(session, in, out)){
                // websocket handshake was successful. Don't write anything to output
                // as we want to abstract the handshake request message from the handler.
                in.position(in.limit());
                return true;
            }
            else{
                // message is from a native socket. Simply wrap and pass through.
                resultBuffer = IoBuffer.wrap(in.array(), 0, in.limit());
                in.position(in.limit());
                session.setAttribute(WebSocketUtils.SessionAttribute, false);
            }
            out.write(resultBuffer);
        }
        else if(session.containsAttribute(WebSocketUtils.SessionAttribute) && true==(Boolean)session.getAttribute(WebSocketUtils.SessionAttribute)){            
            // there is incoming data from the websocket. Decode and send to handler or next filter.     
            int startPos = in.position();
            resultBuffer = buildWSDataBuffer(in, session);
            if(resultBuffer == null){
                // There was not enough data in the buffer to parse. Reset the in buffer
                // position and wait for more data before trying again.
                in.position(startPos);
                return false;
            }
            //转换为byte数组
//            int int1 = resultBuffer.getInt();
           out.write(resultBuffer.array());
        }
        else{
            // session is known to be from a native socket. So
            // simply wrap and pass through.
            resultBuffer = IoBuffer.wrap(in.array(), 0, in.limit());    
            in.position(in.limit());
            out.write(resultBuffer);
        }                        
        return true;
    }
 
Example 17
Source File: RTMPMinaProtocolDecoder.java    From red5-server-common with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws ProtocolCodecException {
    // get the connection from the session
    String sessionId = (String) session.getAttribute(RTMPConnection.RTMP_SESSION_ID);
    log.trace("Session id: {}", sessionId);
    // connection verification routine
    @SuppressWarnings("unchecked")
    IConnectionManager<RTMPConnection> connManager = (IConnectionManager<RTMPConnection>) ((WeakReference<?>) session.getAttribute(RTMPConnection.RTMP_CONN_MANAGER)).get();
    RTMPConnection conn = (RTMPConnection) connManager.getConnectionBySessionId(sessionId);
    RTMPConnection connLocal = (RTMPConnection) Red5.getConnectionLocal();
    if (connLocal == null || !conn.getSessionId().equals(connLocal.getSessionId())) {
        if (log.isDebugEnabled() && connLocal != null) {
            log.debug("Connection local didn't match session");
        }
    }
    if (conn != null) {
        // set the connection to local if its referred to by this session
        Red5.setConnectionLocal(conn);
        // copy data range from incoming
        if (log.isTraceEnabled()) {
            log.trace("Incoming: in.position {}, in.limit {}, in.remaining {}", new Object[] { in.position(), in.limit(), in.remaining() });
        }
        byte[] arr = new byte[in.remaining()];
        in.get(arr);
        // create a buffer and store it on the session
        IoBuffer buf = (IoBuffer) session.getAttribute("buffer");
        if (buf == null) {
            buf = IoBuffer.allocate(arr.length);
            buf.setAutoExpand(true);
            session.setAttribute("buffer", buf);
        }
        // copy incoming into buffer
        buf.put(arr);
        // flip so we can read
        buf.flip();
        if (log.isTraceEnabled()) {
            //log.trace("Buffer before: {}", Hex.encodeHexString(arr));
            log.trace("Buffers info before: buf.position {}, buf.limit {}, buf.remaining {}", new Object[] { buf.position(), buf.limit(), buf.remaining() });
        }
        // get the connections decoder lock
        final Semaphore lock = conn.getDecoderLock();
        try {
            // acquire the decoder lock
            lock.acquire();
            // construct any objects from the decoded bugger
            List<?> objects = decoder.decodeBuffer(conn, buf);
            log.trace("Decoded: {}", objects);
            if (objects != null) {
                int writeCount = 0;
                for (Object object : objects) {
                    out.write(object);
                    writeCount++;
                }
                log.trace("Wrote {} objects", writeCount);
            }
        } catch (Exception e) {
            log.error("Error during decode", e);
        } finally {
            lock.release();
            // clear local
            Red5.setConnectionLocal(null);
        }
        if (log.isTraceEnabled()) {
            //log.trace("Buffer after: {}", Hex.encodeHexString(Arrays.copyOfRange(buf.array(), buf.position(), buf.limit())));
            log.trace("Buffers info after: buf.position {}, buf.limit {}, buf.remaining {}", new Object[] { buf.position(), buf.limit(), buf.remaining() });
        }
    } else {
        log.debug("Closing and skipping decode for unregistered connection: {}", sessionId);
        session.closeNow();
        log.debug("Session closing: {} reading: {} writing: {}", session.isClosing(), session.isReadSuspended(), session.isWriteSuspended());
    }
}
 
Example 18
Source File: AbstractCommandHandler.java    From CXTouch with GNU General Public License v3.0 4 votes vote down vote up
protected <T extends ClientConnection> T getConnection(IoSession session) {
    return (T) session.getAttribute(IApplication.CLIENT_SESSION);
}
 
Example 19
Source File: MaplePacketEncoder.java    From mapleLemon with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
    MapleClient client = (MapleClient) session.getAttribute(MapleClient.CLIENT_KEY);

    if (client != null) {
        byte[] input = (byte[]) message;

        if (ServerProperties.ShowPacket()) {
            int packetLen = input.length;
            int pHeader = readFirstByte(input);
            boolean 记录 = true;
            for (final SendPacketOpcode recv : SendPacketOpcode.values()) {
                if (recv.getValue() == pHeader) {
                    if (SendPacketOpcode.isSpamHeader(recv)) {//暂时记录怪物和角色移动
                        记录 = false;
                    }
                    break;
                }
            }
            if (记录 ) {
                String pHeaderStr = Integer.toHexString(pHeader).toUpperCase();
                pHeaderStr = StringUtil.getLeftPaddedStr(pHeaderStr, '0', 4);
                String op = lookupRecv(pHeader);
                String Recv = "[服务端发送] " + op + "  [0x" + pHeaderStr + "]  (" + packetLen + "字节)  " + FileoutputUtil.CurrentReadable_Time() + "\r\n";

                if (packetLen <= 60000) {
                    String RecvTo = Recv + HexTool.toString(input) + "\r\n" + HexTool.toStringFromAscii(input);
                    FileoutputUtil.packetLog(FileoutputUtil.PacketLog, RecvTo);
                    System.out.print(Recv);

                    if (!ServerProperties.SendPacket(op, pHeaderStr)) {

                        String SendTos = "\r\n时间:" + FileoutputUtil.CurrentReadable_Time() + "\r\n";
                        if ((op.equals("GIVE_BUFF")) || (op.equals("CANCEL_BUFF"))) {
                            FileoutputUtil.packetLog(FileoutputUtil.SkillBuff, SendTos + RecvTo);
                        } else if (op.endsWith("PLAYER_INTERACTION")) {
                            FileoutputUtil.packetLog(FileoutputUtil.玩家互动封包, SendTos + RecvTo);
                        }
                    }
                } else {
                    FileoutputUtil.log(Recv + HexTool.toString(new byte[]{input[0], input[1]}) + "...\r\n");
                }
            }
        }

        byte[] unencrypted = new byte[input.length];
        System.arraycopy(input, 0, unencrypted, 0, input.length);
        byte[] ret = new byte[unencrypted.length + 4];
        Lock mutex = client.getLock();
        mutex.lock();
        try {
            byte[] header = client.getSendCrypto().getPacketHeader(unencrypted.length);
            client.getSendCrypto().crypt(unencrypted);
            System.arraycopy(header, 0, ret, 0, 4);
        } finally {
            mutex.unlock();
        }
        System.arraycopy(unencrypted, 0, ret, 4, unencrypted.length);
        out.write(IoBuffer.wrap(ret));

    } else {
        out.write(IoBuffer.wrap((byte[]) message));
    }
}
 
Example 20
Source File: SslFilter.java    From neoscada with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Returns the underlying {@link SSLSession} for the specified session.
 *
 * @return <tt>null</tt> if no {@link SSLSession} is initialized yet.
 */
public SSLSession getSslSession(IoSession session) {
    return (SSLSession) session.getAttribute(SSL_SESSION);
}