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

The following examples show how to use org.apache.mina.core.session.IoSession#removeAttribute() . 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: MINAStatCollector.java    From Openfire with Apache License 2.0 6 votes vote down vote up
private void removeSession( IoSession session )
{
    // remove the session from the list of polled sessions
    polledSessions.remove( session );

    // add the bytes processed between last polling and session closing
    // prevent non seen byte with non-connected protocols like HTTP and datagrams
    IoSessionStat sessStat = ( IoSessionStat ) session.removeAttribute( KEY );

    if (sessStat != null) {
        totalMsgWritten.addAndGet(session.getWrittenMessages() - sessStat.lastMessageWrite);
        totalMsgRead.addAndGet(session.getReadMessages() - sessStat.lastMessageRead);
        totalBytesWritten.addAndGet(session.getWrittenBytes() - sessStat.lastByteWrite);
        totalBytesRead.addAndGet(session.getReadBytes() - sessStat.lastByteRead);
    }
}
 
Example 2
Source File: RTMPEIoFilter.java    From red5-client with Apache License 2.0 6 votes vote down vote up
/**
 * Provides connection completion.
 * 
 * @param session
 * @param conn
 * @param rtmp
 * @param handshake
 */
private static void completeConnection(IoSession session, RTMPMinaConnection conn, RTMP rtmp, OutboundHandshake handshake) {
    if (handshake.useEncryption()) {
        // set encryption flag the rtmp state
        rtmp.setEncrypted(true);
        // add the ciphers
        log.debug("Adding ciphers to the session");
        session.setAttribute(RTMPConnection.RTMPE_CIPHER_IN, handshake.getCipherIn());
        session.setAttribute(RTMPConnection.RTMPE_CIPHER_OUT, handshake.getCipherOut());
    }
    // set state to indicate we're connected
    conn.getState().setState(RTMP.STATE_CONNECTED);
    log.debug("Connected, removing handshake data");
    // remove handshake from session now that we are connected
    session.removeAttribute(RTMPConnection.RTMP_HANDSHAKE);
    // add protocol filter as the last one in the chain
    log.debug("Adding RTMP protocol filter");
    session.getFilterChain().addAfter("rtmpeFilter", "protocolFilter", new ProtocolCodecFilter(new RTMPMinaCodecFactory()));
    // get the rtmp handler
    BaseRTMPClientHandler handler = (BaseRTMPClientHandler) session.getAttribute(RTMPConnection.RTMP_HANDLER);
    handler.connectionOpened(conn);
}
 
Example 3
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 4
Source File: DefaultIoFilterChain.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
private void callNextExceptionCaught(Entry entry, IoSession session, Throwable cause) {
    // Notify the related future.
    ConnectFuture future = (ConnectFuture) session.removeAttribute(SESSION_CREATED_FUTURE);
    if (future == null) {
        try {
            IoFilter filter = entry.getFilter();
            NextFilter nextFilter = entry.getNextFilter();
            filter.exceptionCaught(nextFilter, session, cause);
        } catch (Throwable e) {
            LOGGER.warn("Unexpected exception from exceptionCaught handler.", e);
        }
    } else {
        // Please note that this place is not the only place that
        // calls ConnectFuture.setException().
        session.close(true);
        future.setException(cause);
    }
}
 
Example 5
Source File: WebSocketHandler.java    From red5-websocket with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void sessionClosed(IoSession session) throws Exception {
    log.trace("Session {} closed", session.getId());
    // remove connection from scope
    WebSocketConnection conn = (WebSocketConnection) session.removeAttribute(Constants.CONNECTION);
    if (conn != null) {
        // remove from the manager
        WebSocketPlugin plugin = (WebSocketPlugin) PluginRegistry.getPlugin("WebSocketPlugin");
        if (plugin != null) {
            String path = conn.getPath();
            if (path != null) {
                WebSocketScopeManager manager = (WebSocketScopeManager) session.removeAttribute(Constants.MANAGER);
                if (manager == null) {
                    manager = plugin.getManager(path);
                }
                if (manager != null) {
                    manager.removeConnection(conn);
                } else {
                    log.debug("WebSocket manager was not found");
                }
            } else {
                log.debug("WebSocket connection path was null");
            }
        } else {
            log.debug("WebSocket plugin was not found");
        }
    } else {
        log.debug("WebSocket connection was null");
    }
    super.sessionClosed(session);
}
 
Example 6
Source File: DeviceIoHandlerAdapter.java    From CXTouch with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void sessionClosed(IoSession session) throws Exception {
    DefaultDeviceConnection connection = (DefaultDeviceConnection) session.getAttribute(CLIENT_SESSION);
    if (connection != null) {
        session.removeAttribute(CLIENT_SESSION);
        if (connection == application.getDeviceConnection(connection.getId())) {
            connection.close();
        }
    }
}
 
Example 7
Source File: TestTupleDecoder.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
/**
 * Decode bytes an attribute at a time, once enough information exists to
 * maintain a tuple This code maintains state in the session as attributes,
 * namely:
 * <UL>
 * <LI>tuple - The partially initialized tuple to be sent to the next
 * handler in the chain.
 * <LI>attributeIndex - The next attribute to be decoded
 * </UL>
 */
@Override
protected boolean doDecode(IoSession session, IoBuffer in,
        ProtocolDecoderOutput out) throws Exception {

    Integer testerId = null;

    if (!session.containsAttribute("testerId")) {
        if (in.remaining() < 4)
            return false;

        testerId = in.getInt();
    }

    if (!in.prefixedDataAvailable(4)) {
        if (testerId != null)
            session.setAttribute("testerId", testerId);
        return false;
    }

    if (testerId == null) {
        testerId = (Integer) session.removeAttribute("testerId");
    }

    int tupleLength = in.getInt();

    byte[] tupleData = new byte[tupleLength];
    in.get(tupleData);

    out.write(new TestTuple(testerId, tupleData));

    return in.remaining() >= 4;
}
 
Example 8
Source File: MINAStatCollector.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Stop collecting stats. all the {@link IoSessionStat} object will be removed of the
 * polled session attachements.
 */
public void stop()
{
    synchronized (this)
    {
        service.removeListener( serviceListener );

        // stop worker
        worker.stop = true;
        worker.interrupt();
        while( worker.isAlive() )
        {
            try
            {
                worker.join();
            }
            catch( InterruptedException e )
            {
                //ignore since this is shutdown time
            }
        }

        for (IoSession session : polledSessions) {
            session.removeAttribute(KEY);
        }
        polledSessions.clear();
    }
}
 
Example 9
Source File: SslFilter.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception {
	SslHandler sslHandler = getSslSessionHandler(session);

	try {
		boolean needsFlush = true;
		synchronized (sslHandler) {
			if (!isSslStarted(session))
				sslHandler.scheduleFilterWrite(nextFilter, writeRequest);
			else if (session.containsAttribute(DISABLE_ENCRYPTION_ONCE)) { // don't encrypt the data if encryption is disabled
				session.removeAttribute(DISABLE_ENCRYPTION_ONCE); // remove the marker attribute because it is temporary
				sslHandler.scheduleFilterWrite(nextFilter, writeRequest);
			} else { // otherwise, encrypt the buffer
				if (sslHandler.isWritingEncryptedData())
					sslHandler.scheduleFilterWrite(nextFilter, writeRequest); // data already encrypted; simply return buffer
				else if (sslHandler.isHandshakeComplete()) { // SSL encrypt
					sslHandler.encrypt(((IoBuffer)writeRequest.writeRequestMessage()).buf());
					IoBuffer encryptedBuffer = sslHandler.fetchOutNetBuffer();
					sslHandler.scheduleFilterWrite(nextFilter, new EncryptedWriteRequest(writeRequest, encryptedBuffer));
				} else {
					if (session.isConnected())
						sslHandler.schedulePreHandshakeWriteRequest(nextFilter, writeRequest); // handshake not complete yet
					needsFlush = false;
				}
			}
		}

		if (needsFlush)
			sslHandler.flushScheduledEvents();
	} catch (SSLException se) {
		sslHandler.release();
		throw se;
	}
}
 
Example 10
Source File: MapleServerHandler.java    From mapleLemon with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void sessionClosed(final IoSession session) throws Exception {
    MapleClient client = (MapleClient) session.getAttribute(MapleClient.CLIENT_KEY);
    if (client != null) {
        try {
            int countRows = ManagerSin.jTable1.getRowCount();//获取当前表格总行数
            for (int i = 0; i < countRows; i++) {
                int AID = (Integer) ManagerSin.jTable1.getValueAt(i, 0);
                if (AID == client.getAccID()) {
                    ((DefaultTableModel) ManagerSin.jTable1.getModel()).removeRow(i);
                    break;
                }
            }
        } catch (Exception e) {
            FileoutputUtil.outputFileError(FileoutputUtil.GUI_Ex_Log, e);
        }

        try {
            client.disconnect(true, (channel == MapleServerHandler.CASH_SHOP_SERVER));
        } finally {
            World.Client.removeClient(client);
            session.close(true);
            session.removeAttribute(MapleClient.CLIENT_KEY);
            session.removeAttribute(MaplePacketDecoder.DECODER_STATE_KEY);
        }
    }
    super.sessionClosed(session);
}
 
Example 11
Source File: TextLineDecoder.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void dispose(IoSession session) throws Exception {
    Context ctx = (Context) session.getAttribute(CONTEXT);

    if (ctx != null) {
        session.removeAttribute(CONTEXT);
    }
}
 
Example 12
Source File: DefaultIoFilterChain.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void sessionCreated(NextFilter nextFilter, IoSession session) throws Exception {
    try {
        session.getHandler().sessionCreated(session);
    } finally {
        // Notify the related future.
        ConnectFuture future = (ConnectFuture) session.removeAttribute(SESSION_CREATED_FUTURE);
        if (future != null) {
            future.setSession(session);
        }
    }
}
 
Example 13
Source File: GameContext.java    From gameserver with Apache License 2.0 5 votes vote down vote up
/**
 * Deregister an user from game server.
 * The session key will be removed from database.
 * 
 * For AI and proxy based session, the behaviour is different, 
 * because one IoSession will bear many users' session.
 * 
 * @param session
 * @param user
 */
public void deregisterUserByIoSession(IoSession session) {
	SessionKey sessionKey = (SessionKey)session.getAttribute(Constant.SESSION_KEY);
	session.removeAttribute(Constant.USER_KEY);
	deregisterUserBySessionKey(sessionKey);
	
	ArrayList<SessionKey> proxySessionKeys = (ArrayList<SessionKey>)session.getAttribute(
			SessionManager.PROXY_SESSION_KEYS);
	if ( proxySessionKeys != null ) {
		ArrayList<SessionKey> tempList = new ArrayList<SessionKey>(proxySessionKeys);
		for ( SessionKey proxySessionKey: tempList ) {
			deregisterUserBySessionKey(proxySessionKey);
		}
	}
}
 
Example 14
Source File: TimedEndDecoder.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Clear the end-of-frame detection for this session
 * 
 * @param session
 *            the session
 */
public void clear ( final IoSession session )
{
    logger.trace ( "Clear for session: {}", session );
    final Context ctx = getTimedContext ( session, false );
    if ( ctx != null )
    {
        ctx.clear ();
        unregisterContext ( ctx );
        session.removeAttribute ( CONTEXT );
    }
}
 
Example 15
Source File: TimedEndDecoder.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void finishDecode ( final IoSession session, final ProtocolDecoderOutput out ) throws Exception
{
    // remove the context from the session and kill the cyclic check
    final Context ctx = (Context)session.removeAttribute ( CONTEXT );
    if ( ctx != null )
    {
        unregisterContext ( ctx );
        ctx.dispose ();
    }
}
 
Example 16
Source File: MapleSessionCoordinator.java    From HeavenMS with GNU Affero General Public License v3.0 5 votes vote down vote up
public void closeSession(IoSession session, Boolean immediately) {
    MapleClient client = getSessionClient(session);
    if (client == null) {
        client = fetchInTransitionSessionClient(session);
    }
    
    String hwid = (String) session.removeAttribute(MapleClient.CLIENT_NIBBLEHWID); // making sure to clean up calls to this function on login phase
    onlineRemoteHwids.remove(hwid);
    
    hwid = (String) session.removeAttribute(MapleClient.CLIENT_HWID);
    onlineRemoteHwids.remove(hwid);
    
    if (client != null) {
        if (hwid != null) { // is a game session
            onlineClients.remove(client.getAccID());
        } else {
            MapleClient loggedClient = onlineClients.get(client.getAccID());
            
            // do not remove an online game session here, only login session
            if (loggedClient != null && loggedClient.getSessionId() == client.getSessionId()) {
                onlineClients.remove(client.getAccID());
            }
        }
    }
    
    if (immediately != null) {
        session.close(immediately);
    }
    
    // session.removeAttribute(MapleClient.CLIENT_REMOTE_ADDRESS); No real need for removing String property on closed sessions
}
 
Example 17
Source File: KeepAliveFilter.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
private void resetStatus(IoSession session) {
    session.getConfig().setReaderIdleTime(0);
    session.getConfig().setWriterIdleTime(0);
    session.getConfig().setIdleTime(interestedIdleStatus, getRequestInterval());
    session.removeAttribute(WAITING_FOR_RESPONSE);
}
 
Example 18
Source File: SslFilter.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws SSLException {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("{}: Writing Message : {}", getSessionInfo(session), writeRequest);
    }

    boolean needsFlush = true;
    SslHandler handler = getSslSessionHandler(session);
    synchronized (handler) {
        if (!isSslStarted(session)) {
            handler.scheduleFilterWrite(nextFilter, writeRequest);
        }
        // Don't encrypt the data if encryption is disabled.
        else if (session.containsAttribute(DISABLE_ENCRYPTION_ONCE)) {
            // Remove the marker attribute because it is temporary.
            session.removeAttribute(DISABLE_ENCRYPTION_ONCE);
            handler.scheduleFilterWrite(nextFilter, writeRequest);
        } else {
            // Otherwise, encrypt the buffer.
            IoBuffer buf = (IoBuffer) writeRequest.getMessage();

            if (handler.isWritingEncryptedData()) {
                // data already encrypted; simply return buffer
                handler.scheduleFilterWrite(nextFilter, writeRequest);
            } else if (handler.isHandshakeComplete()) {
                // SSL encrypt
                int pos = buf.position();
                handler.encrypt(buf.buf());
                buf.position(pos);
                IoBuffer encryptedBuffer = handler.fetchOutNetBuffer();
                handler.scheduleFilterWrite(nextFilter, new EncryptedWriteRequest(writeRequest, encryptedBuffer));
            } else {
                if (session.isConnected()) {
                    // Handshake not complete yet.
                    handler.schedulePreHandshakeWriteRequest(nextFilter, writeRequest);
                }
                needsFlush = false;
            }
        }
    }

    if (needsFlush) {
        handler.flushScheduledEvents();
    }
}
 
Example 19
Source File: WebSocketDecoder.java    From red5-websocket with Apache License 2.0 4 votes vote down vote up
/**
 * Try parsing the message as a websocket handshake request. If it is such a request, then send the corresponding handshake response (as in Section 4.2.2 RFC 6455).
 */
@SuppressWarnings("unchecked")
private boolean doHandShake(IoSession session, IoBuffer in) {
    if (log.isDebugEnabled()) {
        log.debug("Handshake: {}", in);
    }
    // incoming data
    byte[] data = null;
    // check for existing HS data
    if (session.containsAttribute(Constants.WS_HANDSHAKE)) {
        byte[] tmp = (byte[]) session.getAttribute(Constants.WS_HANDSHAKE);
        // size to hold existing and incoming
        data = new byte[tmp.length + in.remaining()];
        System.arraycopy(tmp, 0, data, 0, tmp.length);
        // get incoming bytes
        in.get(data, tmp.length, in.remaining());
    } else {
        // size for incoming bytes
        data = new byte[in.remaining()];
        // get incoming bytes
        in.get(data);
    }
    // ensure the incoming data is complete (ends with crlfcrlf)
    byte[] tail = Arrays.copyOfRange(data, data.length - 4, data.length);
    if (!Arrays.equals(tail, Constants.END_OF_REQ)) {
        // accumulate the HS data
        session.setAttribute(Constants.WS_HANDSHAKE, data);
        return false;
    }
    // create the connection obj
    WebSocketConnection conn = new WebSocketConnection(session);
    // mark as secure if using ssl
    if (session.getFilterChain().contains("sslFilter")) {
        conn.setSecure(true);
    }
    try {
        Map<String, Object> headers = parseClientRequest(conn, new String(data));
        if (log.isTraceEnabled()) {
            log.trace("Header map: {}", headers);
        }
        if (!headers.isEmpty() && headers.containsKey(Constants.WS_HEADER_KEY)) {
            // add the headers to the connection, they may be of use to implementers
            conn.setHeaders(headers);
            // add query string parameters
            if (headers.containsKey(Constants.URI_QS_PARAMETERS)) {
                conn.setQuerystringParameters((Map<String, Object>) headers.remove(Constants.URI_QS_PARAMETERS));
            }
            // check the version
            if (!"13".equals(headers.get(Constants.WS_HEADER_VERSION))) {
                log.info("Version 13 was not found in the request, communications may fail");
            }
            // get the path 
            String path = conn.getPath();
            // get the scope manager
            WebSocketScopeManager manager = (WebSocketScopeManager) session.getAttribute(Constants.MANAGER);
            if (manager == null) {
                WebSocketPlugin plugin = (WebSocketPlugin) PluginRegistry.getPlugin("WebSocketPlugin");
                manager = plugin.getManager(path);
            }
            // store manager in the current session
            session.setAttribute(Constants.MANAGER, manager);
            // TODO add handling for extensions

            // TODO expand handling for protocols requested by the client, instead of just echoing back
            if (headers.containsKey(Constants.WS_HEADER_PROTOCOL)) {
                boolean protocolSupported = false;
                String protocol = (String) headers.get(Constants.WS_HEADER_PROTOCOL);
                log.debug("Protocol '{}' found in the request", protocol);
                // add protocol to the connection
                conn.setProtocol(protocol);
                // TODO check listeners for "protocol" support
                Set<IWebSocketDataListener> listeners = manager.getScope(path).getListeners();
                for (IWebSocketDataListener listener : listeners) {
                    if (listener.getProtocol().equals(protocol)) {
                        //log.debug("Scope has listener support for the {} protocol", protocol);
                        protocolSupported = true;
                        break;
                    }
                }
                log.debug("Scope listener does{} support the '{}' protocol", (protocolSupported ? "" : "n't"), protocol);
            }
            // add connection to the manager
            manager.addConnection(conn);
            // prepare response and write it to the directly to the session
            HandshakeResponse wsResponse = buildHandshakeResponse(conn, (String) headers.get(Constants.WS_HEADER_KEY));
            // pass the handshake response to the ws connection so it can be sent outside the io thread and allow the decode to complete
            conn.sendHandshakeResponse(wsResponse);
            // remove the chunk attr
            session.removeAttribute(Constants.WS_HANDSHAKE);
            return true;
        }
        // set connection as native / direct
        conn.setType(ConnectionType.DIRECT);
    } catch (Exception e) {
        // input is not a websocket handshake request
        log.warn("Handshake failed", e);
    }
    return false;
}
 
Example 20
Source File: ProxyFilter.java    From neoscada with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Called when the filter is removed from the filter chain.
 * Cleans the {@link ProxyIoSession} instance from the session.
 * 
 * @param chain the filter chain
 * @param name the name assigned to this filter
 * @param nextFilter the next filter
 */
@Override
public void onPreRemove(final IoFilterChain chain, final String name, final NextFilter nextFilter) {
    IoSession session = chain.getSession();
    session.removeAttribute(ProxyIoSession.PROXY_SESSION);
}