Java Code Examples for org.apache.mina.core.buffer.IoBuffer#position()

The following examples show how to use org.apache.mina.core.buffer.IoBuffer#position() . 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: TestRTMPProtocolDecoder.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecodeBuffer() {
    log.debug("\ntestDecodeBuffer");
    RTMPProtocolDecoder dec = new RTMPProtocolDecoder();
    List<Object> objs;
    RTMPConnection conn = new RTMPMinaConnection();
    conn.getState().setState(RTMP.STATE_CONNECTED);
    conn.setHandler(this);
    IoBuffer p00 = IoBuffer.wrap(IOUtils.hexStringToByteArray(
            "8639ae8685ad4e802fb905a7918b480416b013e0632e41773e6ba30a1ee089ddb94df6eff6b59aa6251a2707215a2907dc6b51a749ff6680b37792b6c302d43e80f4780361ab7b3c79de5f917aece673e6192e0d45606a5a56dc23ee8113b3381a5d428074f461db71f8caaefa650517809b63edc8412c1f88b4e4d43584ca491a89dfdbb78df1b00c1cedc8e2139fe831becd70527adf4d17760c1cbfff47a1116aaa8f603d3f5319a0688bbc215c1cae1cfb06b6546abd4b76cc7f32cbc84b4531ba2f539d6ae5c4c081bcc51a73b7c14881f8b6bddb480d8a4430b98577f15d31215480d6ebb9cb56931ad3703c2bf024c943b3c45c18717d467387141cdcc88f389548bc335b10ead0daf8e8c69e67f43099ab1f5f2afcb343c08d4b065ec7ce3a437d9891ec8388155d5bdae8dcfd6b4419df2d9c7ca584511e240cc6b1f04ccc098a74d5037c921e4f5916affa17ff71daed20d621687b12bd3f7fcb8f538360b39eb237ca05ada13dc433dc10c2504c55e5ca2e6528b3279eb49e4629218acfc33fce315c58533076d7e3fff6e49650d4283c8fa4ee766f93fc3d10b10bd10b8c2393e2a1da4e6c53dcc5ddbd6efd7b844b7546b0472346b9229cdb6e8d45f70f1e6d23b96cbb2c41fcd486e25fef021e19568c4617248e58ca195fb7aad5ca34dcf27ac7f03dc71a8b4831d1bbb273f6bba56ed9cdf49eef6c45df5071d19d9e8e23fb33b34a65648141cd61db72f79fa7944e3232cd8e30ba310d566fdac6d51b683a3c27af315ca5dc0f614d62c6672e97c036d181e00d6cf08b41a130d7a24783ad616593dc10753959529657f94aec63fa073ae24afe44b2d7075164ebc25305db954607b92c1c7ded5f88e587227ce411010292b6e392aeaeca456d64dadec73cac5de51ec2d3b530db0cdb9869fbdabe1f0aae10bcc1479dc927178a323ac0b2c1def11a086605ee0a66d5a9f1652b5b5860cdbd3594c8e2511c004d8704ccb2732197f37e687753ce0ed00717f20ca6e7076fd4d06b49ba8c665a2adc41e702753225868ace398baebb6944c29c149b838fb71b1e8c20ed3c9561129867c56bc800be10f8dba659f37bbe2242b0cbdcf342396e5ee61f327e7759500d4647e313937c81809b602af08493812ca199698ed35de9ebeded83e1ef5d8f8ad56c368acd7a6d7a05118541bf9d60bc3e45d64431a7700770c814f48f5dcd1c35270a5288b8cbde9333b5b8c40dfd6f0d31d51bea52e0bc6e6e4f46b1bfe85268a494a83d20668829dcfa492325e5f372f45a74bc19c9be07eda5bb1060376b0563081f541801b7d7ce5f7408e5bb11f63d0638419f7cb8aaaa55afa32dfb1e4f0df11fc355ad6c30405b8824f8fff87feeb3b5390cde76040008bb422200a571cd0c19fda9df620ad6ca881c833728081e7cefecc78b280cc06b4c7de3d1c9cebc04d84e1c43fb9fc8b52cc07e0eb15012872c0739322b1da9d7888b6c0f968863ac571837fd63457f98d574665e3cbe1f3b497fb03d1ab8e481985732de26051919d0aba7f18281d8f512b05a625746e4dd50e0c4be16ab4b59aa3cf24e1648ee9d74e4f3b2a92fc7828a5eb2040a706d52e354fb079df3062d404c46fb78de4931caac381020c5bf6b38fecdc5f7d66c3ea3fb087f4ed8ac98a81a24a42053282c7524c2953a5885c1ff5d736d46c472d318312f2a427dc3526fd513c88dbb8583d607031c0a2825f9e74428b859d8874e0cb013b458b27d549a41e4330682dac90e073b79c458dcb2cba317f816bd2dabdcee96d77ab6466021a23a932d134ba33279956aae938787a3a59216b53d50dc0554fe34b5f51d1e050f84e03a7442b29604684291a2ee79198a3911f8a54a1e47c0bf9ec25114f60dae43d4aa4639e5a5c89010ba3884014c2721cab878795f22ba8136f7d4685c9a5c348bda08b60a1ff1afe6d5578d52f5051eeafa9e3b9501701a272a880aaeb30fbc2db66a5e48d7c811a56c9a809c92567d8a10472c142f3dc38c0123e20ed3feb067a550e0a997b38061e191a3bb5b47a04ef70fdd94e69bfc9be160d8a8cc7dc163e8d595cc987c1d676a7b543f56305be60921c19113be5ea988c864b636e216c1c6d71319e0c96b58eb619ac63016ffb97761b79a3eea0016cfacadc7c10300000100014d1400000000020007636f6e6e656374003ff0000000000000030003617070020003766f640008666c61736856657202000e4c4e582032302c302c302c323836000673776655726c020036687474703a2f2f6c6f63616c686f73743a353038302f766f642f6d696e69706c617965722e7377662f5b5b44594e414d49435d5d2f320005746355c3726c02001972746d703a2f2f6c6f63616c686f73743a313933352f766f640004667061640100000c6361706162696c697469657300406de00000000000000b617564696f436f646563730040abee0000000000000b766964656f436f6465637300406f800000000000000d766964656f46756e6374696f6e003ff00000000000c30000077061676555726c020024687474703a2f2f6c6f63616c686f73743a353038302f766f642f696e6465782e68746d6c000e6f626a656374456e636f64696e67004008000000000000000009"));
    p00.position(1536);
    objs = dec.decodeBuffer(conn, p00);
    log.debug("Objects #00: {}", objs);
    assertNotNull("Objects should not be null", objs);
    assertFalse("Objects should not be empty", objs.isEmpty());
    assertEquals("Method should be 'connect'", "connect", ((Invoke) ((Packet) objs.get(0)).getMessage()).getCall().getServiceMethodName());

    IoBuffer p01 = IoBuffer.wrap(IOUtils.hexStringToByteArray(
            "030000000001431400000000020007636f6e6e656374003ff0000000000000030003617070020003766f640008666c61736856657202000e4c4e582032302c302c302c323836000673776655726c020036687474703a2f2f6c6f63616c686f73743a353038302f766f642f6d696e69706c617965722e7377662f5b5b44594e414d49435d5d2f320005746355c3726c02001972746d703a2f2f6c6f63616c686f73743a313933352f766f640004667061640100000c6361706162696c697469657300406de00000000000000b617564696f436f646563730040abee0000000000000b766964656f436f6465637300406f800000000000000d766964656f46756e6374696f6e003ff00000000000c30000077061676555726c02001a687474703a2f2f6c6f63616c686f73743a353038302f766f642f000e6f626a656374456e636f64696e6700400800000000000000000902fffe410000040500000000009896800300003100001a11000000000002000c63726561746553747265616d00400000000000000005"));
    objs = dec.decodeBuffer(conn, p01);
    log.debug("Objects #01: {}", objs);
}
 
Example 2
Source File: Output.java    From red5-io with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public void writeByteArray(ByteArray array) {
    writeAMF3();
    buf.put(AMF3.TYPE_BYTEARRAY);
    if (hasReference(array)) {
        putInteger(getReferenceId(array) << 1);
        return;
    }
    storeReference(array);
    IoBuffer data = array.getData();
    putInteger(data.limit() << 1 | 1);
    byte[] tmp = new byte[data.limit()];
    int old = data.position();
    try {
        data.position(0);
        data.get(tmp);
        buf.put(tmp);
    } finally {
        data.position(old);
    }
}
 
Example 3
Source File: TextLineEncoder.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
    CharsetEncoder encoder = (CharsetEncoder) session.getAttribute(ENCODER);

    if (encoder == null) {
        encoder = charset.newEncoder();
        session.setAttribute(ENCODER, encoder);
    }

    String value = (message == null ? "" : message.toString());
    IoBuffer buf = IoBuffer.allocate(value.length()).setAutoExpand(true);
    buf.putString(value, encoder);

    if (buf.position() > maxLineLength) {
        throw new IllegalArgumentException("Line length: " + buf.position());
    }

    buf.putString(delimiter.getValue(), encoder);
    buf.flip();
    out.write(buf);
}
 
Example 4
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 5
Source File: ObjectSerializationOutputStream.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
public void writeObject(Object obj) throws IOException {
    IoBuffer buf = IoBuffer.allocate(64, false);
    buf.setAutoExpand(true);
    buf.putObject(obj);

    int objectSize = buf.position() - 4;
    if (objectSize > maxObjectSize) {
        throw new IllegalArgumentException("The encoded object is too big: " + objectSize + " (> " + maxObjectSize
                + ')');
    }

    out.write(buf.array(), 0, buf.position());
}
 
Example 6
Source File: TextLineDecoder.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void discard(IoBuffer in) {
    if (Integer.MAX_VALUE - in.remaining() < overflowPosition) {
        overflowPosition = Integer.MAX_VALUE;
    } else {
        overflowPosition += in.remaining();
    }

    in.position(in.limit());
}
 
Example 7
Source File: PrefixedStringEncoder.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
    String value = (String) message;
    IoBuffer buffer = IoBuffer.allocate(value.length()).setAutoExpand(true);
    buffer.putPrefixedString(value, prefixLength, charset.newEncoder());
    if (buffer.position() > maxDataLength) {
        throw new IllegalArgumentException("Data length: " + buffer.position());
    }
    buffer.flip();
    out.write(buffer);
}
 
Example 8
Source File: SerializeUtils.java    From red5-server-common with Apache License 2.0 5 votes vote down vote up
public static byte[] ByteBufferToByteArray(IoBuffer buf) {
    byte[] byteBuf = new byte[buf.limit()];
    int pos = buf.position();
    buf.rewind();
    buf.get(byteBuf);
    buf.position(pos);
    return byteBuf;
}
 
Example 9
Source File: ImmutableTag.java    From red5-server-common with Apache License 2.0 5 votes vote down vote up
public static ImmutableTag build(byte dataType, int timestamp, IoBuffer data) {
    if (data != null) {
        byte[] body = new byte[data.limit()];
        int pos = data.position();
        data.get(body);
        data.position(pos);
        return new ImmutableTag(dataType, timestamp, body);
    } else {
        return new ImmutableTag(dataType, timestamp, null);
    }
}
 
Example 10
Source File: TestITCHVisitorPositive.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
/**
 * Test decode message testString from bytes and check Alpha_notrim
 */
@Test
public void testStringAlphaNotrimDecode(){
       byte[] array = { 58, 0, 1, 48, 0, 0, 0, 0,
               46, 13, 102, 102, 115, 116, 49, 32,
               32, 32, 49, 48, 58, 52, 57, 58,
               48, 48, 77, 111, 110, 32, 74, 117,
               108, 32, 48, 52, 32, 49, 52, 58,
               48, 50, 58, 51, 48, 32, 77, 83,
               75, 32, 50, 48, 49, 54, 0, 0,
               0, 0, 0, 0, 0, 0, 0, 0, };
  		IoBuffer toDecode = IoBuffer.wrap( array );
	toDecode.order(ByteOrder.LITTLE_ENDIAN);
	toDecode.position(0);

	IoSession decodeSession = new DummySession();
	MockProtocolDecoderOutput decoderOutput = new MockProtocolDecoderOutput();
	try{
		boolean decodableResult = codec.doDecode( decodeSession, toDecode, decoderOutput );
		Assert.assertTrue( "Decoding error.", decodableResult);
		IMessage message=(IMessage) decoderOutput.getMessageQueue().element();
		@SuppressWarnings("unchecked")
           List<IMessage> result = message.getField(ITCHMessageHelper.SUBMESSAGES_FIELD_NAME);
		Assert.assertEquals(2, result.size());
		Assert.assertEquals(1, (int)Integer.valueOf(result.get(1).getField("Alpha_notrim").toString().trim()));
	}catch(Exception e){
		e.printStackTrace(System.err);
		logger.error(e.getMessage(),e);
		Assert.fail(e.getMessage());
	}
}
 
Example 11
Source File: SumkProtocolDecoder.java    From sumk with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
		throws ProtocolDecoderException, CharacterCodingException {
	if (in.remaining() < 5) {
		return false;
	}
	final int pos = in.position();
	if (!this.innerDecode(session, in, out)) {
		in.position(pos);
		return false;
	}
	return true;
}
 
Example 12
Source File: FIXCodec.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
public static String getFixString(IoBuffer in) throws MessageParseException {
 int offset = in.position();
    byte[] buffer = new byte[in.remaining()];

    in.get(buffer);

    String out = new String(buffer, 0, buffer.length, Charset.forName(CharsetSupport.getCharset()));

    int beginStringIdx = out.indexOf("8=FIX");

    if(beginStringIdx == -1) {
        in.position(offset);
        return null;
    }

    if(beginStringIdx > 0) {
        in.position(offset + beginStringIdx);
        throw new MessageParseException("BeginString index is higher than 0", out);
    }

    int nextBeginStringIdx = out.indexOf("8=FIX", beginStringIdx + 1);

    if(nextBeginStringIdx != -1) {
        out = out.substring(0, nextBeginStringIdx);
    }

    int checkSumIdx = out.indexOf(SOH + "10=");
    int sohIdx = out.indexOf(SOH, checkSumIdx + 1);

    if(checkSumIdx == -1 || sohIdx == -1) {
        if(nextBeginStringIdx != -1) {
            in.position(nextBeginStringIdx);
            throw new MessageParseException("CheckSum is absent or invalid", out);
        }

        in.position(offset);
        return null;
    }

    sohIdx++;

    in.position(offset + sohIdx);

    if(sohIdx < out.length()) {
        out = out.substring(0, sohIdx);
    }

    sohIdx = out.indexOf(SOH);
    int lengthIdx = out.indexOf("9=");

    if(lengthIdx != sohIdx + 1) {
        throw new MessageParseException("BodyLength is absent or not a second tag", out);
    }

    sohIdx = out.indexOf(SOH, lengthIdx);

    try {
        int bodyLength = Integer.parseInt(out.substring(lengthIdx + 2, sohIdx));

        if(bodyLength != checkSumIdx - sohIdx) {
            throw new MessageParseException("BodyLength value differs from actual message length", out);
        }
    } catch(Exception e) {
        throw new MessageParseException("BodyLength value is invalid", out);
    }

    return out;
}
 
Example 13
Source File: TextLineDecoder.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Decode a line using the delimiter defined by the caller
 */
private void decodeNormal(Context ctx, IoSession session, IoBuffer in, ProtocolDecoderOutput out)
        throws CharacterCodingException, ProtocolDecoderException {
    int matchCount = ctx.getMatchCount();

    // Try to find a match
    int oldPos = in.position();
    int oldLimit = in.limit();

    while (in.hasRemaining()) {
        byte b = in.get();

        if (delimBuf.get(matchCount) == b) {
            matchCount++;

            if (matchCount == delimBuf.limit()) {
                // Found a match.
                int pos = in.position();
                in.limit(pos);
                in.position(oldPos);

                ctx.append(in);

                in.limit(oldLimit);
                in.position(pos);

                if (ctx.getOverflowPosition() == 0) {
                    IoBuffer buf = ctx.getBuffer();
                    buf.flip();
                    buf.limit(buf.limit() - matchCount);

                    try {
                        writeText(session, buf.getString(ctx.getDecoder()), out);
                    } finally {
                        buf.clear();
                    }
                } else {
                    int overflowPosition = ctx.getOverflowPosition();
                    ctx.reset();
                    throw new RecoverableProtocolDecoderException("Line is too long: " + overflowPosition);
                }

                oldPos = pos;
                matchCount = 0;
            }
        } else {
            // fix for DIRMINA-506 & DIRMINA-536
            in.position(Math.max(0, in.position() - matchCount));
            matchCount = 0;
        }
    }

    // Put remainder to buf.
    in.position(oldPos);
    ctx.append(in);

    ctx.setMatchCount(matchCount);
}
 
Example 14
Source File: ConsumeToCrLfDecodingState.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
public DecodingState decode(IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    int beginPos = in.position();
    int limit = in.limit();
    int terminatorPos = -1;

    for (int i = beginPos; i < limit; i++) {
        byte b = in.get(i);
        if (b == CR) {
            lastIsCR = true;
        } else {
            if (b == LF && lastIsCR) {
                terminatorPos = i;
                break;
            }
            lastIsCR = false;
        }
    }

    if (terminatorPos >= 0) {
        IoBuffer product;

        int endPos = terminatorPos - 1;

        if (beginPos < endPos) {
            in.limit(endPos);

            if (buffer == null) {
                product = in.slice();
            } else {
                buffer.put(in);
                product = buffer.flip();
                buffer = null;
            }

            in.limit(limit);
        } else {
            // When input contained only CR or LF rather than actual data...
            if (buffer == null) {
                product = IoBuffer.allocate(0);
            } else {
                product = buffer.flip();
                buffer = null;
            }
        }
        in.position(terminatorPos + 1);
        return finishDecode(product, out);
    }

    in.position(beginPos);

    if (buffer == null) {
        buffer = IoBuffer.allocate(in.remaining());
        buffer.setAutoExpand(true);
    }

    buffer.put(in);

    if (lastIsCR) {
        buffer.position(buffer.position() - 1);
    }

    return this;
}
 
Example 15
Source File: FrameDecoder.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 output ) throws Exception
{
    logger.trace ( "decode data - session: {}, data: {}", session, data );

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

    final int position = data.position ();

    final byte version = data.get ( position ); // peek at version
    if ( version != 0x01 )
    {
        throw new IllegalStateException ( String.format ( "Version 0x%02x is not supported.", version ) );
    }

    final int frameTypeOrdinal = data.get ( position + 1 ); // peek at frame type
    final FrameType frameType = FrameType.values ()[frameTypeOrdinal]; // may case an exception, that is ok then

    final int dataLength = data.getInt ( position + 2 ); // we need to look at "here" + 2

    logger.trace ( "Data length: {}, remainingData: {}", dataLength, data.remaining () - 6 );

    if ( data.remaining () < HEADER_SIZE + dataLength )
    {
        return false;
    }

    // consume fields
    data.get (); // version - #0
    data.get (); // frame type - #1
    data.getInt (); // dataLength - #2

    // data - #6
    final IoBuffer frameData = data.getSlice ( dataLength ); // this also consumes the buffer 'data'

    final Frame frame = new Frame ( frameType, frameData );

    logger.trace ( "Decoded frame: {} ... {} bytes remaining", frame, data.remaining () );
    output.write ( frame );

    return true;
}
 
Example 16
Source File: AxisTest.java    From red5-rtsp-restreamer with Apache License 2.0 4 votes vote down vote up
private void sendAVCDecoderConfig(int timecode) {

		IoBuffer buffV = IoBuffer.allocate(_pCodecSetup.length);
		buffV.setAutoExpand(true);
		for (int p = 0; p < _pCodecSetup.length; p++)
			buffV.put((byte) _pCodecSetup[p]);
		buffV.flip();

		buffV.position(0);

		IRTMPEvent video = new VideoData(buffV);

		video.setTimestamp(timecode);

		video.setHeader(new Header());

		if (output != null)
			output.dispatchEvent(video);

	}
 
Example 17
Source File: DhcpDecoder.java    From dhcp4j with Apache License 2.0 4 votes vote down vote up
@Override
public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws DhcpException, IOException {
    out.write(decoder.decode(in.buf()));
    in.position(in.limit());    // Consume the remaining bytes, as they will be handed back to us.
}
 
Example 18
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 19
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 20
Source File: TPKTFilter.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void messageReceived ( final NextFilter nextFilter, final IoSession session, final Object message ) throws Exception
{
    if ( ! ( message instanceof IoBuffer ) )
    {
        nextFilter.messageReceived ( session, message );
        return;
    }

    final IoBuffer in = (IoBuffer)message;
    final IoBuffer sessionBuffer = getSessionBuffer ( session );

    // first add to the session buffer (may be optimized later)
    sessionBuffer.position ( sessionBuffer.limit () );
    sessionBuffer.put ( in );
    sessionBuffer.flip ();

    while ( sessionBuffer.remaining () >= 4 )
    {
        final int len = sessionBuffer.getUnsignedShort ( 2 );
        if ( sessionBuffer.remaining () < len )
        {
            logger.debug ( "Next packet requires {} bytes", new Object[] { len } );
            // not enough data for body
            return;
        }

        // convert
        final IoBuffer data = IoBuffer.allocate ( len - 4 );
        sessionBuffer.get (); // version
        sessionBuffer.get (); // reserved
        sessionBuffer.getUnsignedShort (); // length

        sessionBuffer.get ( data.array () );

        nextFilter.messageReceived ( session, data );

        logger.debug ( "{} bytes left in session buffer", sessionBuffer.remaining () );
    }

    if ( sessionBuffer.hasRemaining () )
    {
        sessionBuffer.compact ();
    }
    else
    {
        sessionBuffer.clear ().flip ();
    }
}