Java Code Examples for org.apache.mina.filter.codec.ProtocolDecoderOutput#write()

The following examples show how to use org.apache.mina.filter.codec.ProtocolDecoderOutput#write() . 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: CommandDecoder.java    From mina with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    if (in.prefixedDataAvailable(2)) {
        short length = in.getShort();//获取包长

        byte[] bytes = new byte[length];
        in.get(bytes);
        byte[] msgidBytes = new byte[Constants.COMMAND_LENGTH];
        System.arraycopy(bytes, 0, msgidBytes, 0, Constants.COMMAND_LENGTH);
        int msgid = NumberUtils.bytesToInt(msgidBytes);
        if (msgid != 0) {
            //通过工厂方法生成指定消息类型的指令对象
            BaseCommand command = CommandFactory.createCommand(msgid);

            byte[] cmdBodyBytes = new byte[length - Constants.COMMAND_LENGTH];
            System.arraycopy(bytes, Constants.COMMAND_LENGTH, cmdBodyBytes, 0, length - Constants.COMMAND_LENGTH);
            command.bodyFromBytes(cmdBodyBytes);
            out.write(command);
            return true;
        }
    }

    return false;
}
 
Example 2
Source File: ProtocolDecoderImpl.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
private boolean processDataUpdate ( final IoSession session, final IoBuffer data, final ProtocolDecoderOutput out ) throws ProtocolCodecException
{
    final int len = messageLength ( data );
    if ( len < 0 )
    {
        return false;
    }

    final int count = data.getUnsignedShort ();
    final List<DataUpdate.Entry> entries = new ArrayList<DataUpdate.Entry> ( count );
    for ( int i = 0; i < count; i++ )
    {
        entries.add ( decodeDataUpdateEntry ( data, session ) );
    }

    out.write ( new DataUpdate ( entries ) );

    return true;
}
 
Example 3
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 4
Source File: CommandDecoder.java    From mina with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    if (in.prefixedDataAvailable(2)) {
        short length = in.getShort();//获取包长

        byte[] bytes = new byte[length];
        in.get(bytes);
        byte[] msgidBytes = new byte[Constants.COMMAND_LENGTH];
        System.arraycopy(bytes, 0, msgidBytes, 0, Constants.COMMAND_LENGTH);
        int msgid = NumberUtils.bytesToInt(msgidBytes);
        if (msgid != 0) {
            //通过工厂方法生成指定消息类型的指令对象
            BaseCommand command = CommandFactory.createCommand(msgid);

            byte[] cmdBodyBytes = new byte[length - Constants.COMMAND_LENGTH];
            System.arraycopy(bytes, Constants.COMMAND_LENGTH, cmdBodyBytes, 0, length - Constants.COMMAND_LENGTH);
            command.bodyFromBytes(cmdBodyBytes);
            out.write(command);
            return true;
        }
    }

    return false;
}
 
Example 5
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 6
Source File: ProtobufDecoder.java    From gameserver with Apache License 2.0 6 votes vote down vote up
/**
	 * Decode the message.
	 */
	@Override
	protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
//		XinqiMessage message = (XinqiMessage) session.getAttribute(DECODER_STATE_KEY);
//		if ( message == null ) {
//			message = new XinqiMessage();
//			session.setAttribute(DECODER_STATE_KEY, message);
//		}
		
		Object obj = ProtobufDecoder.decodeXinqiMessage(in);
		if ( obj instanceof XinqiMessage ) {
			XinqiMessage message = (XinqiMessage)obj;
			if ( message == null ) {
				return false;
			}
			out.write(message);
			return true;
		}
		
//		session.setAttribute(DECODER_STATE_KEY, null);
		return false;
	}
 
Example 7
Source File: MinaUtil.java    From seed with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    Context ctx = this.getContext(session);
    IoBuffer buffer = ctx.innerBuffer;
    int messageCount = ctx.getMessageCount();
    while(in.hasRemaining()){    //判断position和limit之间是否有元素
        buffer.put(in.get());    //get()读取buffer的position的字节,然后position+1
        if(messageCount++ == 5){ //约定:报文的前6个字符串表示报文总长度,不足6位则左侧补0
            buffer.flip();       //Set limit=position and position=0 and mark=-1
            //当Server的响应报文中含0x00时,Mina2.x的buffer.getString(fieldSize, decoder)方法会break
            //该方法的处理细节,详见org.apache.mina.core.buffer.AbstractIoBuffer类的第1718行源码,其说明如下
            //Reads a NUL-terminated string from this buffer using the specified decoder and returns it
            //ctx.setMessageLength(Integer.parseInt(buffer.getString(6, decoder)));
            byte[] messageLength = new byte[6];
            buffer.get(messageLength);
            try{
                //请求报文有误时,Server可能返回非约定报文,此时会抛java.lang.NumberFormatException
                ctx.setMessageLength(Integer.parseInt(new String(messageLength, charset)));
            }catch(NumberFormatException e){
                ctx.setMessageLength(in.limit());
            }
            //让两个IoBuffer的limit相等
            buffer.limit(in.limit());
        }
    }
    ctx.setMessageCount(messageCount);
    if(ctx.getMessageLength() == buffer.position()){
        buffer.flip();
        byte[] message = new byte[buffer.limit()];
        buffer.get(message);
        out.write(new String(message, charset));
        ctx.reset();
        return true;
    }else{
        return false;
    }
}
 
Example 8
Source File: BytesDataDecoder.java    From oim-fx with MIT License 5 votes vote down vote up
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
	try {
		if (in.prefixedDataAvailable(4, Integer.MAX_VALUE)) {
			in.mark();// 标记当前位置,以便reset

			int textSize = in.getInt(); // 读取传送过来的消息的长度。ByteBuf
			int bytesSize = in.getInt();
			int totalSize = (textSize + bytesSize);
			if ((totalSize) > in.remaining()) {// 如果消息内容不够,则重置,相当于不读取size
				in.reset();
				return false;// 接收新数据,以拼凑成完整数据
			}

			BytesData bd = new BytesData();

			byte[] textBytes = new byte[textSize]; // 嗯,这时候,我们读到的长度,满足我们的要求了,把传送过来的数据,取出来吧~~
			in.get(textBytes); //

			byte[] bytes = new byte[bytesSize];
			in.get(bytes); //

			String text = new String(textBytes, charset); // 将byte数据转化为我们需要的对象。伪代码,用什么序列化,自行选择

			bd.setMessage(text);
			bd.setBytes(bytes);
			out.write(bd);
			return true;// 接收新数据,以拼凑成完整数据
		}
	} catch (Exception e) {
		in.sweep();
		logger.error("", e);
	}
	return false;
}
 
Example 9
Source File: XMPPDecoder.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
        throws Exception {
    // Get the XML light parser from the IoSession
    XMLLightweightParser parser = (XMLLightweightParser) session.getAttribute(ConnectionHandler.XML_PARSER);
    // Parse as many stanzas as possible from the received data
    parser.read(in);

    if (parser.areThereMsgs()) {
        for (String stanza : parser.getMsgs()) {
            out.write(stanza);
        }
    }
    return !in.hasRemaining();
}
 
Example 10
Source File: ObjectSerializationDecoder.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    if (!in.prefixedDataAvailable(4, maxObjectSize)) {
        return false;
    }

    out.write(in.getObject(classLoader));
    return true;
}
 
Example 11
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 12
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;
}
 
Example 13
Source File: ServerProtocolHTTPDecoder.java    From seed with Apache License 2.0 4 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_HTTP);
    token.setFullMessage(fullMessage);
    if(fullMessage.startsWith("GET")){
        if(fullMessage.startsWith("GET / HTTP/1.1\r\n") || fullMessage.startsWith("GET / HTTP/1.0\r\n")){
            token.setBusiCode("/");
        }else if(fullMessage.startsWith("GET /favicon.ico HTTP/1.1\r\n") || fullMessage.startsWith("GET /favicon.ico HTTP/1.0\r\n")){
            token.setBusiCode("/favicon.ico");
        }else{
            //GET /login?aa=bb&cc=dd&ee=ff HTTP/1.1
            if(fullMessage.substring(4, fullMessage.indexOf("\r\n")).contains("?")){
                token.setBusiCode(fullMessage.substring(4, fullMessage.indexOf("?")));
                token.setBusiMessage(fullMessage.substring(fullMessage.indexOf("?")+1, this.getHTTPVersionPosition(fullMessage)-1));
            //GET /login HTTP/1.1
            }else{
                token.setBusiCode(fullMessage.substring(4, this.getHTTPVersionPosition(fullMessage)-1));
            }
        }
    }else if(fullMessage.startsWith("POST")){
        //先获取到请求报文头中的Content-Length
        int contentLength = 0;
        if(fullMessage.contains("Content-Length:")){
            String msgLenFlag = fullMessage.substring(fullMessage.indexOf("Content-Length:") + 15);
            if(msgLenFlag.contains("\r\n")){
                contentLength = Integer.parseInt(msgLenFlag.substring(0, msgLenFlag.indexOf("\r\n")).trim());
                if(contentLength > 0){
                    token.setBusiMessage(fullMessage.split("\r\n\r\n")[1]);
                }
            }
        }
        //POST /login?aa=bb&cc=dd&ee=ff HTTP/1.1
        //特别说明一下:此时报文体本应该是空的,即Content-Length=0,但不能排除对方偏偏在报文体中也传了参数
        //特别说明一下:所以这里的处理手段是busiMessage=请求URL中的参数串 + "`" + 报文体中的参数串(如果存在报文体的话)
        if(fullMessage.substring(5, fullMessage.indexOf("\r\n")).contains("?")){
            token.setBusiCode(fullMessage.substring(5, fullMessage.indexOf("?")));
            String urlParam = fullMessage.substring(fullMessage.indexOf("?")+1, this.getHTTPVersionPosition(fullMessage)-1);
            if(contentLength > 0){
                token.setBusiMessage(urlParam + "`" + fullMessage.split("\r\n\r\n")[1]);
            }else{
                token.setBusiMessage(urlParam);
            }
        //POST /login HTTP/1.1
        }else{
            token.setBusiCode(fullMessage.substring(5, this.getHTTPVersionPosition(fullMessage)-1));
        }
    }
    out.write(token);
    return MessageDecoderResult.OK;
}
 
Example 14
Source File: MassProtocolDecoder.java    From game-server with MIT License 4 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * 不包括消息长度
 */
protected void decodeBytes(int length, IoBuffer ib, ProtocolDecoderOutput out) {
    byte[] bytes = new byte[length];
    ib.get(bytes);
    out.write(bytes);
}
 
Example 15
Source File: AIProtocolCodecFilterTest.java    From gameserver with Apache License 2.0 4 votes vote down vote up
private SessionAIMessage encodeAndDecode(SessionAIMessage sessionMessage) throws Exception {
	
	AIProtobufEncoder encoder = new AIProtobufEncoder();
	AIProtobufDecoder decoder = new AIProtobufDecoder();
	final ArrayList<Object> results = new ArrayList<Object>();
	
	IoSession session = createNiceMock(IoSession.class);
	expect(session.getTransportMetadata()).andReturn(
			new DefaultTransportMetadata("testprovider", "default", 
					false, true, InetSocketAddress.class, DefaultSocketSessionConfig.class, 
					SessionMessage.class)).anyTimes();
	
	ProtocolEncoderOutput out = createNiceMock(ProtocolEncoderOutput.class);
	out.write(anyObject());
	expectLastCall().andAnswer(new IAnswer<Object>() {
		@Override
		public Object answer() throws Throwable {
			results.add(getCurrentArguments()[0]);
			return null;
		}
	}).anyTimes();
	
	replay(session);
	replay(out);
	
	encoder.encode(session, sessionMessage, out);
	
	verify(session);
	verify(out);
	
	assertTrue(results.get(0) instanceof IoBuffer );
	
	IoBuffer buffer = (IoBuffer)results.get(0);
	results.remove(0);
	
	ProtocolDecoderOutput deout = createNiceMock(ProtocolDecoderOutput.class);
	deout.write(anyObject());
	expectLastCall().andAnswer(new IAnswer<Object>() {
		@Override
		public Object answer() throws Throwable {
			results.add(getCurrentArguments()[0]);
			return null;
		}
	}).times(1);
	replay(deout);
	
	decoder.decode(session, buffer, deout);
	
	verify(deout);
	
	SessionAIMessage decodeMsg = (SessionAIMessage)results.get(0);
	return decodeMsg;
}
 
Example 16
Source File: ClientProtocolDecoder.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 {
	int readAbleLen = in.remaining();
	if (readAbleLen < 2) {
		return false;
	}
	in.mark(); // 标记阅读位置
	byte[] bs = new byte[2];
	in.get(bs, 0, 2);
	short packageLength = IntUtil.bigEndianByteToShort(bs, 0, 2);
	if (packageLength < 1 || packageLength > maxReadSize) {
		LOGGER.warn("消息包长度为:{}", packageLength);
		in.clear();
		session.closeNow();
		return false;
	}

	if (in.remaining() < packageLength) { // 消息长度不够,重置位置
		in.reset();
		return false;
	}
	// 消息Id(4字节)+protobufLength(4字节)+消息体+时间戳(8字节)+签名数据长度(4字节)+签名数据+截取签名长度(4字节)
	bs = new byte[packageLength];
	in.get(bs);
	int protobufLength = IntUtil.bigEndianByteToInt(bs, 4, 4);
	if (packageLength > protobufLength + 8) {
		LOGGER.debug("消息签名验证");
		if (checkMsgSign(bs, protobufLength)) {
			byte[] datas = new byte[8 + protobufLength];
			System.arraycopy(bs, 0, datas, 0, datas.length);
			out.write(bs);
		} else {
			session.closeNow();
			return false;
		}
	} else {
		out.write(bs);
	}

	// decodeBytes(packageLength, in, out);

	if (!checkMsgFrequency(session)) {
		return false;
	}

	return true;
}
 
Example 17
Source File: HttpDecoderTest.java    From gameserver with Apache License 2.0 4 votes vote down vote up
@Test
public void testDoDecodeWithPOST() throws Exception {
	String request = 
			"POST /cmcccharge HTTP/1.1\r\n" +
			"Host: localhost\r\n" +
			"\r\n"+
			"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"+
			"<request>\r\n"+
			"	<hRet>0</hRet>\r\n"+
			"	<status>1800</status>\r\n"+
			"	<transIDO>12345678901234567</transIDO>\r\n"+
			"	<versionId>100</versionId>\r\n"+
			"	<userId>12345678</userId>\r\n"+
			"	<cpServiceId>120123002000</cpServiceId>\r\n"+
			"	<consumeCode>120123002001</consumeCode>\r\n"+
			"	<cpParam>0000000000000000</cpParam>\r\n"+
			"</request>\r\n"+
			"\r\n";
	final HttpMessage expect = new HttpMessage();
	expect.setRequestUri("/cmcccharge");
	
	HttpDecoder decoder = new HttpDecoder();
	
	IoSession session = TestUtil.createIoSession();
	//Set mock behavior
	expect(session.getAttribute(eq("HttpDecoder.Session"))).andReturn(null).anyTimes();
	expect(session.setAttribute(eq("HttpDecoder.Session"), anyObject())).andReturn(null).anyTimes();
	replay(session);
	
	ProtocolDecoderOutput out = createNiceMock(ProtocolDecoderOutput.class);
	out.write(anyObject());
	expectLastCall().andAnswer(new IAnswer<Object>() {
		public Object answer() {
			HttpMessage message = (HttpMessage)getCurrentArguments()[0];
			assertTrue(compareHttpMessage(expect, message));
			assertFalse(message.isHead());
			return null;
		}
	});
	replay(out);
	
	IoBuffer in = IoBuffer.wrap(request.getBytes());
	
	int l = in.remaining();
	boolean result = true;
	while ( result ) {
		result = decoder.doDecode(session, in, out);
	}
	
	verify(session);
	verify(out);
	
	assertTrue(true);
}
 
Example 18
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 19
Source File: ProtocolDecoderImpl.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected boolean doDecode ( final IoSession session, final IoBuffer data, final ProtocolDecoderOutput out ) throws Exception
{
    byte marker1;
    byte marker2;

    do
    {
        if ( data.remaining () < 2 ) // we may only eat the start when there could be a packet after it
        {
            return false;
        }

        // peek marker
        marker1 = data.get ( data.position () + 0 );
        marker2 = data.get ( data.position () + 1 );

        // TODO: re-think the idea of just skipping

        if ( marker1 != 0x12 || marker2 != 0x02 )
        {
            data.skip ( 2 ); // eat garbage
        }
    } while ( marker1 != 0x12 || marker2 != 0x02 );

    if ( data.remaining () < 3 )
    {
        return false;
    }

    data.order ( Sessions.isLittleEndian ( session ) ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN );

    final byte command = data.get ( data.position () + 2 );
    switch ( command )
    {
        case Messages.MC_HELLO:
            return processHello ( session, data, out );
        case Messages.MC_WELCOME:
            return processWelcome ( session, data, out );
        case Messages.MC_READ_ALL:
            out.write ( new ReadAll () );
            return true;
        case Messages.MC_DATA_UPDATE:
            return processDataUpdate ( session, data, out );
        case Messages.MC_START_BROWSE:
            out.write ( new SubscribeBrowse () );
            return true;
        case Messages.MC_STOP_BROWSE:
            out.write ( new UnsubscribeBrowse () );
            return true;
        case Messages.MC_NS_ADDED:
            return processBrowseAdded ( session, data, out );
        case Messages.MC_WRITE_COMMAND:
            return processWriteCommand ( session, data, out );
        case Messages.MC_WRITE_RESULT:
            return processWriteResult ( session, data, out );
    }

    throw new ProtocolCodecException ( String.format ( "Message code %02x is unkown", command ) );
}
 
Example 20
Source File: GameProtocolCodecFilterTest.java    From gameserver with Apache License 2.0 4 votes vote down vote up
private void encodeAndDecode(XinqiMessage response, boolean checkDecoder) throws Exception {
	ProtobufEncoder encoder = new ProtobufEncoder();
	ProtobufDecoder decoder = new ProtobufDecoder();
	final ArrayList<Object> results = new ArrayList<Object>();
	
	IoSession session = createNiceMock(IoSession.class);
	expect(session.getTransportMetadata()).andReturn(
			new DefaultTransportMetadata("testprovider", "default", 
					false, true, InetSocketAddress.class, DefaultSocketSessionConfig.class, 
					SessionMessage.class)).anyTimes();
	
	ProtocolEncoderOutput out = createNiceMock(ProtocolEncoderOutput.class);
	out.write(anyObject());
	expectLastCall().andAnswer(new IAnswer<Object>() {
		@Override
		public Object answer() throws Throwable {
			results.add(getCurrentArguments()[0]);
			return null;
		}
	});
	
	replay(session);
	replay(out);
	
	encoder.encode(session, response, out);
	
	verify(session);
	verify(out);
	
	assertTrue(results.get(0) instanceof IoBuffer );
	
	IoBuffer buffer = (IoBuffer)results.get(0);
	results.remove(0);
	
	ProtocolDecoderOutput deout = createNiceMock(ProtocolDecoderOutput.class);
	if ( checkDecoder ) {
		deout.write(anyObject());
		expectLastCall().andAnswer(new IAnswer<Object>() {
			@Override
			public Object answer() throws Throwable {
				results.add(getCurrentArguments()[0]);
				return null;
			}
		}).times(1);
	}
	replay(deout);
	
	decoder.decode(session, buffer, deout);
	
	verify(deout);
	
	if ( checkDecoder ) {
		XinqiMessage decodeMsg = (XinqiMessage)results.get(0);
		assertEquals(response.payload.getClass(), decodeMsg.payload.getClass());
	}
}