org.apache.mina.filter.codec.ProtocolDecoderOutput Java Examples

The following examples show how to use org.apache.mina.filter.codec.ProtocolDecoderOutput. 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: ProtocolDecoderImpl.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
private boolean processWriteResult ( final IoSession session, final IoBuffer data, final ProtocolDecoderOutput out ) throws ProtocolCodecException
{
    final int len = messageLength ( data );
    if ( len < 0 )
    {
        return false;
    }

    try
    {
        final int operationId = data.getInt ();
        final int errorCode = data.getUnsignedShort ();
        final String errorMessage = decodeString ( session, data );

        out.write ( new WriteResult ( operationId, errorCode, errorMessage ) );
    }
    catch ( final CharacterCodingException e )
    {
        throw new ProtocolCodecException ( e );
    }

    return true;
}
 
Example #2
Source File: IntegerDecodingState.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public DecodingState decode(IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    while (in.hasRemaining()) {
        switch (counter) {
        case 0:
            firstByte = in.getUnsigned();
            break;
        case 1:
            secondByte = in.getUnsigned();
            break;
        case 2:
            thirdByte = in.getUnsigned();
            break;
        case 3:
            counter = 0;
            return finishDecode((firstByte << 24) | (secondByte << 16) | (thirdByte << 8) | in.getUnsigned(), out);
        default:
            throw new InternalError();
        }
        counter++;
    }

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

    final int registerNumber = data.getUnsignedShort ();
    final int operationId = data.getInt ();
    final Variant value = decodeVariant ( session, data );

    out.write ( new WriteCommand ( registerNumber, value, operationId ) );

    return true;
}
 
Example #4
Source File: SkippingState.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public DecodingState decode(IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    int beginPos = in.position();
    int limit = in.limit();
    for (int i = beginPos; i < limit; i++) {
        byte b = in.get(i);
        if (!canSkip(b)) {
            in.position(i);
            int answer = this.skippedBytes;
            this.skippedBytes = 0;
            return finishDecode(answer);
        }

        skippedBytes++;
    }

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

    final byte version = data.get ();
    if ( version != 0x01 )
    {
        throw new ProtocolCodecException ( String.format ( "Protocol version %s is unsupported", version ) );
    }

    final short nodeId = data.getShort ();
    final EnumSet<Hello.Features> features = data.getEnumSetShort ( Hello.Features.class );

    out.write ( new Hello ( nodeId, features ) );

    return true;
}
 
Example #6
Source File: ProtocolDecoderImpl.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
private boolean processBrowseAdded ( 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<BrowseAdded.Entry> entries = new ArrayList<BrowseAdded.Entry> ( count );

    for ( int i = 0; i < count; i++ )
    {
        entries.add ( decodeBrowserAddEntry ( data, session ) );
    }

    out.write ( new BrowseAdded ( entries ) );

    return true;
}
 
Example #7
Source File: DataCodecDecoder.java    From oim-fx with MIT License 6 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 size = in.getInt();
			if ((size) > in.remaining()) {// 如果消息内容不够,则重置,相当于不读取size
				in.reset();
				return false;// 接收新数据,以拼凑成完整数据
			}
			byte[] bodyByte = new byte[size];
			in.get(bodyByte, 0, size);
			String xml = new String(bodyByte, charset);
			out.write(xml);
			return true;// 接收新数据,以拼凑成完整数据
		}
	} catch (Exception e) {
		in.sweep();
		logger.error("", e);
	}
	return false;
}
 
Example #8
Source File: FASTCodec.java    From sailfish-core 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.hasRemaining()) {
		return false;
	}
	int position = in.position();
	try {
		if (doRealDecode(session, in, out)) {
			return true;
		}
	} catch (Exception e) {
		logger.error("Can not decode message", e);
	}
	in.position(position);
	return false;
}
 
Example #9
Source File: WebMessageDecoder.java    From cim with Apache License 2.0 6 votes vote down vote up
private void handleHandshake(IoSession iosession, IoBuffer in, ProtocolDecoderOutput out) {
	
	byte[] data = new byte[in.remaining()];
	in.get(data);
	String message = new String(data);
	
	/*
	 * 重要,握手响应之后,删除标志HANDSHAKE_FRAME,并标记当前session的协议为websocket
	 */
    iosession.setAttribute(SOURCE,WEBSOCKET);
	SentBody body = new SentBody();
	body.setKey(CIMConstant.CLIENT_WEBSOCKET_HANDSHAKE);
	body.setTimestamp(System.currentTimeMillis());
	body.put("key", getSecWebSocketKey(message));
	out.write(body);
}
 
Example #10
Source File: TimedEndDecoder.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
public synchronized void check ()
{
    if ( this.disposed )
    {
        return;
    }

    if ( this.lastData == null )
    {
        return;
    }

    if ( System.currentTimeMillis () - this.lastData > this.timeout )
    {
        final ProtocolDecoderOutput out = this.out;
        TimedEndDecoder.this.clear ( this.session );
        this.decoder.wrapTimeout ( this.session, out );
    }
}
 
Example #11
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 #12
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 #13
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 #14
Source File: WelderDecoder.java    From camelinaction with Apache License 2.0 6 votes vote down vote up
protected boolean doDecode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception {
    if (in.remaining() >= PAYLOAD_SIZE) {
        byte[] buf = new byte[in.remaining()];
        in.get(buf);
        
        // first 7 bytes are the sensor ID, last is the status
        // and the result message will look something like
        // MachineID=2371748;Status=Good
        StringBuilder sb = new StringBuilder();
        sb.append("MachineID=")
        .append(new String(buf, 0, PAYLOAD_SIZE - 1)).append(";")
        .append("Status=");
        if (buf[PAYLOAD_SIZE - 1] == '1') {
            sb.append("Good");
        } else {
            sb.append("Failure");
        }
        out.write(sb.toString());
        return true;
    } else {
        return false;
    }
}
 
Example #15
Source File: StructDecoder.java    From javastruct with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected boolean doDecode(IoSession session, ByteBuffer in,
		ProtocolDecoderOutput out) throws Exception {
	
	if(in.prefixedDataAvailable(4, MAX_MESSAGE_SIZE)){
		int len = in.getInt();
		int type = in.getInt();
		byte[] b = new byte[len];
		in.get(b);
		StructMessage m = Messages.getMessage(type);
		JavaStruct.unpack(m, b);
		out.write(m);
		return true;
	}
	
	return false;
}
 
Example #16
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 #17
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 #18
Source File: RpcRequestDecoder.java    From gameserver with Apache License 2.0 6 votes vote down vote up
/**
 * Decode the RpcRequest
 */
protected boolean doDecode(IoSession session, IoBuffer in,
		ProtocolDecoderOutput out) throws Exception {
	
	if (in.prefixedDataAvailable(HEADER_LENGTH, MAX_LENGTH)) {
		RpcMessage.Builder rpcRequestBuilder = RpcMessage.newBuilder();
		int length = in.getInt();
		byte[] bytes = new byte[length];
		in.get(bytes);
		rpcRequestBuilder.mergeFrom(bytes);
		
		out.write(rpcRequestBuilder.build());
		return true;
	} else {
		// not enough data available
		return false;
	}
}
 
Example #19
Source File: MinaDecoder.java    From MiniWeChat-Server with MIT License 5 votes vote down vote up
@Override
	protected boolean doDecode(IoSession ioSession, IoBuffer ioBuffer, ProtocolDecoderOutput output) throws Exception {
		// 如果没有接收完Size部分(4字节),直接返回false
		if (ioBuffer.remaining() < 4)
			return false;
		else {
			// 标记开始位置,如果一条消息没传输完成则返回到这个位置
			ioBuffer.mark();
			
			byteArrayOutputStream = new ByteArrayOutputStream();

			// 读取Size
			byte[] bytes = new byte[4];
			ioBuffer.get(bytes); // 读取4字节的Size
			byteArrayOutputStream.write(bytes);
			int bodyLength = DataTypeTranslater.bytesToInt(bytes, 0) - DataTypeTranslater.INT_SIZE; // 按小字节序转int

			// 如果body没有接收完整,直接返回false
			if (ioBuffer.remaining() < bodyLength) {
				ioBuffer.reset(); // IoBuffer position回到原来标记的地方
				return false;
			} else {
				byte[] bodyBytes = new byte[bodyLength];
				ioBuffer.get(bodyBytes);
//				String body = new String(bodyBytes, "UTF-8");
				byteArrayOutputStream.write(bodyBytes);
				
				// 创建对象
				NetworkPacket packetFromClient = new NetworkPacket(ioSession, byteArrayOutputStream.toByteArray());
				
				output.write(packetFromClient); // 解析出一条消息
				return true;
			}
		}
	}
 
Example #20
Source File: TextLineDecoder.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    Context ctx = getContext(session);

    if (LineDelimiter.AUTO.equals(delimiter)) {
        decodeAuto(ctx, session, in, out);
    } else {
        decodeNormal(ctx, session, in, out);
    }
}
 
Example #21
Source File: ConsumeToEndOfSessionDecodingState.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public DecodingState finishDecode(ProtocolDecoderOutput out) throws Exception {
    try {
        if (buffer == null) {
            buffer = IoBuffer.allocate(0);
        }
        buffer.flip();
        return finishDecode(buffer, out);
    } finally {
        buffer = null;
    }
}
 
Example #22
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 #23
Source File: ConsumeToEndOfSessionDecodingState.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public DecodingState decode(IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    if (buffer == null) {
        buffer = IoBuffer.allocate(256).setAutoExpand(true);
    }

    if (buffer.position() + in.remaining() > maxLength) {
        throw new ProtocolDecoderException("Received data exceeds " + maxLength + " byte(s).");
    }
    buffer.put(in);
    return this;
}
 
Example #24
Source File: ArduinoCodec.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void decodeMessage ( final int sequence, final byte commandCode, final IoBuffer data, final ProtocolDecoderOutput output ) throws ProtocolCodecException
{
    switch ( commandCode )
    {
        case 3:
            decodeResponseConfiguration ( data, output, sequence );
            break;
        case 5:
            decodeResponseData ( data, output, sequence );
            break;
    }

}
 
Example #25
Source File: FixedLengthDecodingState.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public DecodingState finishDecode(ProtocolDecoderOutput out) throws Exception {
    IoBuffer readData;
    if (buffer == null) {
        readData = IoBuffer.allocate(0);
    } else {
        readData = buffer.flip();
        buffer = null;
    }
    return finishDecode(readData, out);
}
 
Example #26
Source File: ModbusRtuDecoder.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void decodeTimeoutFrame ( final IoSession session, final IoBuffer currentFrame, final ProtocolDecoderOutput out )
{
    logger.trace ( "timeout () frame = {}", currentFrame.getHexDump () );

    if ( currentFrame.limit () <= Constants.RTU_HEADER_SIZE )
    {
        throw new ModbusProtocolError ( "frame must be at least 4 bytes long (address + data[] + crc low + crc high" );
    }

    currentFrame.order ( ByteOrder.LITTLE_ENDIAN );
    final int receivedCrc = currentFrame.getUnsignedShort ( currentFrame.limit () - 2 );
    currentFrame.order ( ByteOrder.BIG_ENDIAN );

    final int actualCrc = Checksum.crc16 ( currentFrame.array (), 0, currentFrame.limit () - 2 );
    if ( receivedCrc != actualCrc )
    {
        final String hd = currentFrame.getHexDump ();
        logger.info ( "CRC error - received: {}, calculated: {} - data: {}", receivedCrc, actualCrc, hd );
        throw new ChecksumProtocolException ( String.format ( "CRC error. received: %04x, but actually was: %04x - Data: %s", receivedCrc, actualCrc, hd ) );
    }

    currentFrame.position ( 0 );

    // get unit id
    final byte unitIdentifier = currentFrame.get ();

    final int len = currentFrame.limit () - ( 2 /*crc*/+ 1/*unit id*/);

    final IoBuffer pdu = IoBuffer.allocate ( len );
    for ( int i = 0; i < len; i++ )
    {
        pdu.put ( currentFrame.get () );
    }
    pdu.flip ();

    // decode and send
    logger.trace ( "Decoded PDU - data: {}", pdu.getHexDump () );
    out.write ( new Pdu ( 0, unitIdentifier, pdu ) );
}
 
Example #27
Source File: ConsumeToCrLfDecodingState.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public DecodingState finishDecode(ProtocolDecoderOutput out) throws Exception {
    IoBuffer product;
    // When input contained only CR or LF rather than actual data...
    if (buffer == null) {
        product = IoBuffer.allocate(0);
    } else {
        product = buffer.flip();
        buffer = null;
    }
    return finishDecode(product, out);
}
 
Example #28
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 #29
Source File: AIProtobufDecoder.java    From gameserver with Apache License 2.0 5 votes vote down vote up
/**
 * Decode the message.
 */
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
	// Make sure all the header bytes are ready.
	if ( !in.prefixedDataAvailable(HEADER_LENGTH, MAX_LENGTH) ) {
    return false;
	}
	
	byte[] bytes = new byte[in.getInt()];
	in.get(bytes);
	
	AIMessage aiMessage = AIMessage.parseFrom(bytes);
	
	ByteString sessionBytes = aiMessage.getSession();
	ByteString contentBytes = aiMessage.getContent();
	
	if ( sessionBytes != null && contentBytes != null) {
		SessionKey sessionKey = SessionKey.createSessionKey(sessionBytes.toByteArray());
		XinqiMessage xinqiMessage = XinqiMessage.fromByteArray(contentBytes.toByteArray());
		
		if ( xinqiMessage != null ) {
			SessionAIMessage sessionMessage = new SessionAIMessage();
			sessionMessage.setSessionKey(sessionKey);
			sessionMessage.setMessage(xinqiMessage);
			out.write(sessionMessage);
		}
	} else {
		logger.debug("AIProtocolDecoder sessionBytes or contentBytes is null");
	}
	return true;
}
 
Example #30
Source File: SingleByteDecodingState.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
public DecodingState decode(IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    if (in.hasRemaining()) {
        return finishDecode(in.get(), out);
    }

    return this;
}