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

The following examples show how to use org.apache.mina.core.session.IoSession#setAttribute() . 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: SslFilter.java    From jane with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Executed just before the filter is added into the chain, we do :
 * <ul>
 * <li>check that we don't have a SSL filter already present
 * <li>we update the next filter
 * <li>we create the SSL handler helper class
 * <li>and we store it into the session's Attributes
 * </ul>
 */
@Override
public void onPreAdd(IoFilterChain chain, String name, NextFilter nextFilter) throws SSLException {
	// Check that we don't have a SSL filter already present in the chain
	if (chain.getEntry(SslFilter.class) != null)
		throw new IllegalStateException("only one SSL filter is permitted in a chain");

	// Adding the supported ciphers in the SSLHandler
	if (enabledCipherSuites == null || enabledCipherSuites.length == 0)
		enabledCipherSuites = sslContext.getServerSocketFactory().getSupportedCipherSuites();

	IoSession session = chain.getSession();

	// Create a SSL handler and start handshake.
	SslHandler sslHandler = new SslHandler(this, session);
	sslHandler.init();

	session.setAttribute(SSL_HANDLER, sslHandler);
}
 
Example 2
Source File: DefaultPreprocessor.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
protected void addMessageTimeField(IMessage message, IMessageStructure msgStructure, IoSession session) {
    try {
        String secondsField = getSecondsField();
        String nanosField = getNanoField();
        if (isTimeMessage(msgStructure)) {
            if(msgStructure.getFields().containsKey(secondsField)) {
                session.setAttribute(ITCHMessageHelper.FIELD_SECONDS, message.getField(secondsField));
            } else {
                logger.warn("Message {} [{}] not contains field {}", message.getName(), message.getFieldNames(),
                        secondsField);
            }
        } else if(msgStructure.getFields().containsKey(ITCHMessageHelper.FAKE_FIELD_MESSAGE_TIME)
                && session.containsAttribute(ITCHMessageHelper.FIELD_SECONDS)
                && msgStructure.getFields().containsKey(nanosField)) {
            long seconds = ((Number) ObjectUtils.defaultIfNull(session.getAttribute(ITCHMessageHelper.FIELD_SECONDS), -1l)).longValue();
            if (seconds != -1l) {
                long nanoSeconds = ObjectUtils.defaultIfNull(message.getField(nanosField), 0L);
                LocalDateTime dateTime = toLocalDateTime(seconds, nanoSeconds);
                message.addField(ITCHMessageHelper.FAKE_FIELD_MESSAGE_TIME, dateTime);
            }
        }
    } catch (RuntimeException e) {
        logger.warn("{} field has not been add to message {} ", ITCHMessageHelper.FAKE_FIELD_MESSAGE_TIME, message.getName(), e);
    }
}
 
Example 3
Source File: SslFilter.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Executed just before the filter is added into the chain, we do :
 * <ul>
 * <li>check that we don't have a SSL filter already present
 * <li>we update the next filter
 * <li>we create the SSL handler helper class
 * <li>and we store it into the session's Attributes
 * </ul>
 */
@Override
public void onPreAdd(IoFilterChain parent, String name, NextFilter nextFilter) throws SSLException {
    // Check that we don't have a SSL filter already present in the chain
    if (parent.contains(SslFilter.class)) {
        String msg = "Only one SSL filter is permitted in a chain.";
        LOGGER.error(msg);
        throw new IllegalStateException(msg);
    }

    LOGGER.debug("Adding the SSL Filter {} to the chain", name);

    IoSession session = parent.getSession();
    session.setAttribute(NEXT_FILTER, nextFilter);

    // Create a SSL handler and start handshake.
    SslHandler handler = new SslHandler(this, session);
    handler.init();
    session.setAttribute(SSL_HANDLER, handler);
}
 
Example 4
Source File: HttpServerDecoderImpl.java    From game-server with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
protected boolean doDecode(IoSession session, IoBuffer msg, ProtocolDecoderOutput out) throws Exception {
	/**
	 * 消息已经解析
	 * 谷歌浏览器一次请求存在多次收到消息,还额外请求了/favicon.ico路径
	 */
	if (session.containsAttribute(HTTP_REQUEST)) {
		return false;
	}
	msg.mark();
	HttpRequestImpl rq = parseHttpRequestHead(msg.buf(), msg);
	if (rq != null) {
		out.write(rq);
		session.setAttribute(HTTP_REQUEST, rq);
		// LOG.info("解析成功");
		return true;
	}
	msg.reset();
	return false;
}
 
Example 5
Source File: MinaProtocolEncoder.java    From jforgame with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
	CodecContext context = (CodecContext) session.getAttribute(MinaSessionProperties.CODEC_CONTEXT);
	if (context == null) {
		context = new CodecContext();
		session.setAttribute(MinaSessionProperties.CODEC_CONTEXT, context);
	}
	IoBuffer buffer = writeMessage((Message) message);
	out.write(buffer);
}
 
Example 6
Source File: MapleSessionCoordinator.java    From HeavenMS with GNU Affero General Public License v3.0 5 votes vote down vote up
private static MapleClient fetchInTransitionSessionClient(IoSession session) {
    String remoteHwid = MapleSessionCoordinator.getInstance().getGameSessionHwid(session);
    
    if (remoteHwid != null) {   // maybe this session was currently in-transition?
        int hwidLen = remoteHwid.length();
        if (hwidLen <= 8) {
            session.setAttribute(MapleClient.CLIENT_NIBBLEHWID, remoteHwid);
        } else {
            session.setAttribute(MapleClient.CLIENT_HWID, remoteHwid);
            session.setAttribute(MapleClient.CLIENT_NIBBLEHWID, remoteHwid.substring(hwidLen - 8, hwidLen));
        }
        
        MapleClient client = new MapleClient(null, null, session);
        Integer cid = Server.getInstance().freeCharacteridInTransition(client);
        if (cid != null) {
            try {
                client.setAccID(MapleCharacter.loadCharFromDB(cid, client, false).getAccountID());
            } catch (SQLException sqle) {
                sqle.printStackTrace();
            }
        }
        
        session.setAttribute(MapleClient.CLIENT_KEY, client);
        return client;
    }
    
    return null;
}
 
Example 7
Source File: RTMPMinaIoHandler.java    From red5-client with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void sessionCreated(IoSession session) throws Exception {
    log.debug("Session created");
    // add rtmpe filter, rtmp protocol filter is added upon successful handshake
    session.getFilterChain().addFirst("rtmpeFilter", new RTMPEIoFilter());
    // create a connection
    RTMPMinaConnection conn = createRTMPMinaConnection();
    // set the session on the connection
    conn.setIoSession(session);
    // add the connection
    session.setAttribute(RTMPConnection.RTMP_SESSION_ID, conn.getSessionId());
    // create an outbound handshake, defaults to non-encrypted mode
    OutboundHandshake outgoingHandshake = new OutboundHandshake();
    // add the handshake
    session.setAttribute(RTMPConnection.RTMP_HANDSHAKE, outgoingHandshake);
    // setup swf verification
    if (enableSwfVerification) {
        String swfUrl = (String) handler.getConnectionParams().get("swfUrl");
        log.debug("SwfUrl: {}", swfUrl);
        if (!StringUtils.isEmpty(swfUrl)) {
            outgoingHandshake.initSwfVerification(swfUrl);
        }
    }
    //if handler is rtmpe client set encryption on the protocol state
    //if (handler instanceof RTMPEClient) {
    //rtmp.setEncrypted(true);
    //set the handshake type to encrypted as well
    //outgoingHandshake.setHandshakeType(RTMPConnection.RTMP_ENCRYPTED);
    //}
    // set a reference to the handler on the sesssion
    session.setAttribute(RTMPConnection.RTMP_HANDLER, handler);
    // set a reference to the connection on the client
    handler.setConnection((RTMPConnection) conn);
    // set a connection manager for any required handling and to prevent memory leaking
    RTMPConnManager connManager = (RTMPConnManager) RTMPConnManager.getInstance();
    session.setAttribute(RTMPConnection.RTMP_CONN_MANAGER, new WeakReference<IConnectionManager<RTMPConnection>>(connManager));
}
 
Example 8
Source File: MessageChannelCodecFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private CharsetDecoder getCharsetDecoder ( final IoSession session )
{
    if ( session.containsAttribute ( "charsetDecoder" ) )
    {
        return (CharsetDecoder)session.getAttribute ( "charsetDecoder" );
    }

    final CharsetDecoder decoder = Charset.forName ( "UTF-8" ).newDecoder ();
    session.setAttribute ( "charsetDecoder", decoder );
    return decoder;
}
 
Example 9
Source File: AbstractStreamWriteFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception {
    // If we're already processing a stream we need to queue the WriteRequest.
    if (session.getAttribute(CURRENT_STREAM) != null) {
        Queue<WriteRequest> queue = getWriteRequestQueue(session);
        if (queue == null) {
            queue = new ConcurrentLinkedQueue<WriteRequest>();
            session.setAttribute(WRITE_REQUEST_QUEUE, queue);
        }
        queue.add(writeRequest);
        return;
    }

    Object message = writeRequest.getMessage();

    if (getMessageClass().isInstance(message)) {

        T stream = getMessageClass().cast(message);

        IoBuffer buffer = getNextBuffer(stream);
        if (buffer == null) {
            // End of stream reached.
            writeRequest.getFuture().setWritten();
            nextFilter.messageSent(session, writeRequest);
        } else {
            session.setAttribute(CURRENT_STREAM, message);
            session.setAttribute(CURRENT_WRITE_REQUEST, writeRequest);

            nextFilter.filterWrite(session, new DefaultWriteRequest(buffer));
        }

    } else {
        nextFilter.filterWrite(session, writeRequest);
    }
}
 
Example 10
Source File: KeepAliveFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void sessionIdle(NextFilter nextFilter, IoSession session, IdleStatus status) throws Exception {
    if (status == interestedIdleStatus) {
        if (!session.containsAttribute(WAITING_FOR_RESPONSE)) {
            Object pingMessage = messageFactory.getRequest(session);
            if (pingMessage != null) {
                nextFilter.filterWrite(session, new DefaultWriteRequest(pingMessage));

                // If policy is OFF, there's no need to wait for
                // the response.
                if (getRequestTimeoutHandler() != KeepAliveRequestTimeoutHandler.DEAF_SPEAKER) {
                    markStatus(session);
                    if (interestedIdleStatus == IdleStatus.BOTH_IDLE) {
                        session.setAttribute(IGNORE_READER_IDLE_ONCE);
                    }
                } else {
                    resetStatus(session);
                }
            }
        } else {
            handlePingTimeout(session);
        }
    } else if (status == IdleStatus.READER_IDLE) {
        if (session.removeAttribute(IGNORE_READER_IDLE_ONCE) == null) {
            if (session.containsAttribute(WAITING_FOR_RESPONSE)) {
                handlePingTimeout(session);
            }
        }
    }

    if (forwardEvent) {
        nextFilter.sessionIdle(session, status);
    }
}
 
Example 11
Source File: GameContext.java    From gameserver with Apache License 2.0 5 votes vote down vote up
/**
 * Register a login user with his/her session.
 * The session key will be stored in database.
 * @param session
 * @param user
 */
public void registerUserSession(IoSession session, User user, SessionKey existSessionKey) {
	SessionKey sessionKey = sessionManager.registerSession(session, user, existSessionKey);
	if ( !user.isProxy() ) {
		session.setAttribute(Constant.USER_KEY, user);
	}
	if ( sessionKey != null ) {
		loginUserMap.put(sessionKey, user);
	}
}
 
Example 12
Source File: ProtocolCodecFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Return a reference to the decoder callback. If it's not already created
 * and stored into the session, we create a new instance.
 */
private ProtocolDecoderOutput getDecoderOut(IoSession session, NextFilter nextFilter) {
    ProtocolDecoderOutput out = (ProtocolDecoderOutput) session.getAttribute(DECODER_OUT);

    if (out == null) {
        // Create a new instance, and stores it into the session
        out = new ProtocolDecoderOutputImpl();
        session.setAttribute(DECODER_OUT, out);
    }

    return out;
}
 
Example 13
Source File: StreamIoHandler.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Initializes streams and timeout settings.
 */
@Override
public void sessionOpened(IoSession session) {
    // Set timeouts
    session.getConfig().setWriteTimeout(writeTimeout);
    session.getConfig().setIdleTime(IdleStatus.READER_IDLE, readTimeout);

    // Create streams
    InputStream in = new IoSessionInputStream();
    OutputStream out = new IoSessionOutputStream(session);
    session.setAttribute(KEY_IN, in);
    session.setAttribute(KEY_OUT, out);
    processStreamIo(session, in, out);
}
 
Example 14
Source File: ProxyIoSessionInitializer.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
public void initializeSession(final IoSession session, T future) {
    if (wrappedSessionInitializer != null) {
        wrappedSessionInitializer.initializeSession(session, future);
    }

    if (proxyIoSession != null) {
        proxyIoSession.setSession(session);
        session.setAttribute(ProxyIoSession.PROXY_SESSION, proxyIoSession);
    }
}
 
Example 15
Source File: MdcInjectionFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static Map<String, String> getContext(final IoSession session) {
    Map<String, String> context = (Map<String, String>) session.getAttribute(CONTEXT_KEY);
    if (context == null) {
        context = new ConcurrentHashMap<String, String>();
        session.setAttribute(CONTEXT_KEY, context);
    }
    return context;
}
 
Example 16
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 17
Source File: MapleSessionCoordinator.java    From HeavenMS with GNU Affero General Public License v3.0 4 votes vote down vote up
public AntiMulticlientResult attemptLoginSession(IoSession session, String nibbleHwid, int accountId, boolean routineCheck) {
    if (!YamlConfig.config.server.DETERRED_MULTICLIENT) {
        session.setAttribute(MapleClient.CLIENT_NIBBLEHWID, nibbleHwid);
        return AntiMulticlientResult.SUCCESS;
    }

    String remoteHost = getSessionRemoteHost(session);
    Lock lock = getCoodinatorLock(remoteHost);

    try {
        int tries = 0;
        while (true) {
            if (lock.tryLock()) {
                try {
                    if (pooledRemoteHosts.contains(remoteHost)) {
                        return AntiMulticlientResult.REMOTE_PROCESSING;
                    }

                    pooledRemoteHosts.add(remoteHost);
                } finally {
                    lock.unlock();
                }

                break;
            } else {
                if(tries == 2) {
                    return AntiMulticlientResult.COORDINATOR_ERROR;
                }
                tries++;

                Thread.sleep(1777);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return AntiMulticlientResult.COORDINATOR_ERROR;
    }

    try {
        if (!loginStorage.registerLogin(accountId)) {
            return AntiMulticlientResult.MANY_ACCOUNT_ATTEMPTS;
        }

        if (!routineCheck) {
            if (onlineRemoteHwids.contains(nibbleHwid)) {
                return AntiMulticlientResult.REMOTE_LOGGEDIN;
            }

            if (!attemptAccessAccount(nibbleHwid, accountId, routineCheck)) {
                return AntiMulticlientResult.REMOTE_REACHED_LIMIT;
            }

            session.setAttribute(MapleClient.CLIENT_NIBBLEHWID, nibbleHwid);
            onlineRemoteHwids.add(nibbleHwid);
        } else {
            if (!attemptAccessAccount(nibbleHwid, accountId, routineCheck)) {
                return AntiMulticlientResult.REMOTE_REACHED_LIMIT;
            }
        }

        return AntiMulticlientResult.SUCCESS;
    } finally {
        lock.lock();
        try {
            pooledRemoteHosts.remove(remoteHost);
        } finally {
            lock.unlock();
        }
    }
}
 
Example 18
Source File: ServerConnection.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
public ServerConnection ( final IoSession session )
{
    logger.info ( "Creating new server connection: {}", session );

    this.statistics = new StatisticsImpl ();

    this.session = session;

    this.mxBean = ManagedConnection.register ( new ManagedConnection () {
        @Override
        protected Collection<StatisticEntry> getEntries ()
        {
            return ServerConnection.this.statistics.getEntries ();
        }

        @Override
        public void close ()
        {
            ServerConnection.this.session.close ( false );
        }

        @Override
        public Map<String, String> getTransportProperties ()
        {
            final MessageChannelFilter mcf = (MessageChannelFilter)session.getFilterChain ().get ( MessageChannelFilter.class );
            if ( mcf != null )
            {
                return mcf.getAcceptedProperties ();
            }
            else
            {
                return null;
            }
        }
    }, session.getRemoteAddress (), "org.eclipse.scada.core.server.ngp" );

    this.statistics.setLabel ( STATS_MESSAGES_SENT, "Messages sent" );
    this.statistics.setLabel ( STATS_MESSAGES_RECEIVED, "Messages received" );

    session.setAttribute ( StatisticsFilter.STATS_KEY, this.statistics );
}
 
Example 19
Source File: RTMPMinaCodecFactory.java    From red5-client with Apache License 2.0 4 votes vote down vote up
@Override
public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws ProtocolCodecException {
    log.trace("decode buffer position: {}", in.position());
    // get the connection from the session
    String sessionId = (String) session.getAttribute(RTMPConnection.RTMP_SESSION_ID);
    log.trace("Session id: {}", sessionId);
    RTMPConnection conn = (RTMPConnection) RTMPConnManager.getInstance().getConnectionBySessionId(sessionId);
    Red5.setConnectionLocal(conn);
    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();
    final Semaphore lock = conn.getDecoderLock();
    try {
        // acquire the decoder lock
        lock.acquire();
        // construct any objects from the decoded buffer
        List<?> objects = getDecoder().decodeBuffer(conn, buf);
        log.trace("Decoded: {}", objects);
        if (objects != null) {
            for (Object object : objects) {
                log.trace("Writing {} to decoder output: {}", object, out);
                out.write(object);
            }
        }
        log.trace("Input buffer position: {}", in.position());
    } catch (Exception e) {
        log.error("Error during decode", e);
    } finally {
        lock.release();
        Red5.setConnectionLocal(null);
    }
}
 
Example 20
Source File: WebSocketDecoder.java    From red5-websocket with Apache License 2.0 4 votes vote down vote up
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    IoBuffer resultBuffer;
    WebSocketConnection conn = (WebSocketConnection) session.getAttribute(Constants.CONNECTION);
    if (conn == null) {
        log.debug("Decode start pos: {}", in.position());
        // first message on a new connection, check if its from a websocket or a native socket
        if (doHandShake(session, in)) {
            log.debug("Decode end pos: {} limit: {}", in.position(), in.limit());
            // websocket handshake was successful. Don't write anything to output as we want to abstract the handshake request message from the handler
            if (in.position() != in.limit()) {
                in.position(in.limit());
            }
            return true;
        } else if (session.containsAttribute(Constants.WS_HANDSHAKE)) {
            // more still expected to come in before HS is completed
            return false;
        } else {
            // message is from a native socket. Simply wrap and pass through
            resultBuffer = IoBuffer.wrap(in.array(), 0, in.limit());
            in.position(in.limit());
            out.write(resultBuffer);
        }
    } else if (conn.isWebConnection()) {
        // grab decoding state
        DecoderState decoderState = (DecoderState) session.getAttribute(DECODER_STATE_KEY);
        if (decoderState == null) {
            decoderState = new DecoderState();
            session.setAttribute(DECODER_STATE_KEY, decoderState);
        }
        // there is incoming data from the websocket, decode it
        decodeIncommingData(in, session);
        // this will be null until all the fragments are collected
        WSMessage message = (WSMessage) session.getAttribute(DECODED_MESSAGE_KEY);
        if (log.isDebugEnabled()) {
            log.debug("State: {} message: {}", decoderState, message);
        }
        if (message != null) {
            // set the originating connection on the message
            message.setConnection(conn);
            // write the message
            out.write(message);
            // remove decoded message
            session.removeAttribute(DECODED_MESSAGE_KEY);
        } else {
            // there was not enough data in the buffer to parse
            return false;
        }
    } else {
        // session is known to be from a native socket. So simply wrap and pass through
        byte[] arr = new byte[in.remaining()];
        in.get(arr);
        out.write(IoBuffer.wrap(arr));
    }
    return true;
}