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

The following examples show how to use org.apache.mina.core.buffer.IoBuffer#remaining() . 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: 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 2
Source File: MinaCodecAdapter.java    From JobX with Apache License 2.0 6 votes vote down vote up
@Override
public boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    if (in.limit() <= 0 || in.remaining() < Constants.HEADER_SIZE) {
        return false;
    }
    in.mark();
    int dataLength = in.getInt();

    if (in.remaining() < dataLength) {
        //logger.warn("[JobX]serializer error!body length < {}", dataLength);
        in.reset();
        return false;
    }
    byte[] data = new byte[dataLength];
    in.get(data);
    Object obj =  serializer.deserialize(data,type);
    out.write(obj);
    return true;
}
 
Example 3
Source File: HexDumper.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
public static byte[] peakBytes(IoBuffer in, int lengthLimit) {
	if (lengthLimit == 0) {
		throw new IllegalArgumentException("lengthLimit: " + lengthLimit + " (expected: 1+)");
	}

	boolean truncate = in.remaining() > lengthLimit;
       int size = truncate ? lengthLimit : in.remaining();

       if(size == 0) {
		return new byte[0];
	}

	int mark = in.position();

	byte[] array = new byte[size];

	in.get(array);
	in.position(mark);

	return array;
}
 
Example 4
Source File: ModbusProtocol.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Encode the data from Java byte order to requested modbus byte order
 *
 * @param data
 *            the data to encode
 * @param dataOrder
 *            the target modbus byte order
 * @return the converted data, or the input data if no conversion was
 *         necessary
 */
public static IoBuffer convertData ( final IoBuffer data, final ByteOrder dataOrder )
{
    if ( dataOrder == ByteOrder.BIG_ENDIAN )
    {
        return data;
    }

    final IoBuffer result = IoBuffer.allocate ( data.capacity () );
    result.order ( dataOrder );

    for ( int i = 0; i < data.remaining () / 2; i++ )
    {
        // convert to LITTLE_ENDIAN
        result.putUnsignedShort ( data.getUnsignedShort ( i * 2 ) );
    }

    // the byte order we use is BIG_ENDIAN
    result.order ( ByteOrder.BIG_ENDIAN );

    return result;
}
 
Example 5
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 6
Source File: MsgUtil.java    From game-server with MIT License 5 votes vote down vote up
public static Message buildMessage(Class<? extends Message> clazz, IoBuffer ioBuffer) throws Exception {
	if (ioBuffer.remaining() < 1) {
		return null;
	}
	byte[] bytes = new byte[ioBuffer.remaining()];
	ioBuffer.get(bytes);
	return buildMessage(clazz, bytes);
}
 
Example 7
Source File: DoubleType.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Variant getValue ( final int localOffset, final IoBuffer value )
{
    if ( localOffset == AbstractSourceType.COMMON_HEADER && value.remaining () == DATA_LENGTH )
    {
        return Variant.valueOf ( value.getDouble () );
    }
    return null;
}
 
Example 8
Source File: Packet.java    From red5-websocket with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the packet which just wraps the IoBuffer.
 * 
 * @param buffer
 * @return packet
 */
public static Packet build(IoBuffer buffer) {
    if (buffer.hasArray()) {
        return new Packet(buffer.array());
    }
    byte[] buf = new byte[buffer.remaining()];
    buffer.get(buf);
    return new Packet(buf);
}
 
Example 9
Source File: LongFieldTypeHandler.java    From CXTouch with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Long decode(IoBuffer inBuffer) {
    if (inBuffer.remaining() < 8) {
        return null;
    } else {
        return inBuffer.getLong();
    }
}
 
Example 10
Source File: ShortIntegerType.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Variant getValue ( final int localOffset, final IoBuffer value )
{
    if ( localOffset == AbstractSourceType.COMMON_HEADER && value.remaining () == DATA_LENGTH )
    {
        return Variant.valueOf ( value.getShort () );
    }
    return null;
}
 
Example 11
Source File: DoubleFieldTypeHandler.java    From CXTouch with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Double decode(IoBuffer inBuffer) {
    if (inBuffer.remaining() < 8) {
        return null;
    } else {
        return inBuffer.getDouble();
    }
}
 
Example 12
Source File: ServerProtocolHTTPDecoder.java    From seed with Apache License 2.0 5 votes vote down vote up
@Override
public MessageDecoderResult decodable(IoSession session, IoBuffer in) {
    if(in.remaining() < 5){
        return MessageDecoderResult.NEED_DATA;
    }
    if(session.getLocalAddress().toString().contains(":" + ConfigUtil.INSTANCE.getProperty("server.port.http"))){
        return this.isComplete(in) ? MessageDecoderResult.OK : MessageDecoderResult.NEED_DATA;
    }else{
        return MessageDecoderResult.NOT_OK;
    }
}
 
Example 13
Source File: CacheableImpl.java    From red5-io with Apache License 2.0 5 votes vote down vote up
public CacheableImpl(Object obj) {
    IoBuffer tmp = IoBuffer.allocate(128).setAutoExpand(true);
    tmp.putObject(obj);
    tmp.flip();
    bytes = new byte[tmp.remaining()];
    tmp.get(bytes);
    cached = true;
    tmp.free();
    tmp = null;
}
 
Example 14
Source File: Zlib.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Compress the input. The result will be put in a new buffer.
 *  
 * @param inBuffer the buffer to be compressed. The contents are transferred
 * into a local byte array and the buffer is flipped and returned intact.
 * @return the buffer with the compressed data
 * @throws IOException if the compression of teh buffer failed for some reason
 * @throws IllegalStateException if the mode is not <code>MODE_DEFLATER</code>
 */
public IoBuffer deflate(IoBuffer inBuffer) throws IOException {
    if (mode == MODE_INFLATER) {
        throw new IllegalStateException("not initialized as DEFLATER");
    }

    byte[] inBytes = new byte[inBuffer.remaining()];
    inBuffer.get(inBytes).flip();

    // according to spec, destination buffer should be 0.1% larger
    // than source length plus 12 bytes. We add a single byte to safeguard
    // against rounds that round down to the smaller value
    int outLen = (int) Math.round(inBytes.length * 1.001) + 1 + 12;
    byte[] outBytes = new byte[outLen];

    synchronized (zStream) {
        zStream.next_in = inBytes;
        zStream.next_in_index = 0;
        zStream.avail_in = inBytes.length;
        zStream.next_out = outBytes;
        zStream.next_out_index = 0;
        zStream.avail_out = outBytes.length;

        int retval = zStream.deflate(JZlib.Z_SYNC_FLUSH);
        if (retval != JZlib.Z_OK) {
            outBytes = null;
            inBytes = null;
            throw new IOException("Compression failed with return value : " + retval);
        }

        IoBuffer outBuf = IoBuffer.wrap(outBytes, 0, zStream.next_out_index);

        return outBuf;
    }
}
 
Example 15
Source File: RTMPEIoFilter.java    From red5-client with Apache License 2.0 5 votes vote down vote up
@Override
public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest request) throws Exception {
    RTMPMinaConnection conn = (RTMPMinaConnection) RTMPConnManager.getInstance().getConnectionBySessionId((String) session.getAttribute(RTMPConnection.RTMP_SESSION_ID));
    // filter based on current connection state
    if (conn.getState().getState() == RTMP.STATE_CONNECTED && session.containsAttribute(RTMPConnection.RTMPE_CIPHER_OUT)) {
        Cipher cipher = (Cipher) session.getAttribute(RTMPConnection.RTMPE_CIPHER_OUT);
        IoBuffer message = (IoBuffer) request.getMessage();
        if (!message.hasRemaining()) {
            if (log.isTraceEnabled()) {
                log.trace("Ignoring empty message");
            }
            nextFilter.filterWrite(session, request);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Encrypting message: {}", message);
            }
            byte[] plain = new byte[message.remaining()];
            message.get(plain);
            message.clear();
            message.free();
            // encrypt and write
            byte[] encrypted = cipher.update(plain);
            IoBuffer messageEncrypted = IoBuffer.wrap(encrypted);
            if (log.isDebugEnabled()) {
                log.debug("Encrypted message: {}", messageEncrypted);
            }
            nextFilter.filterWrite(session, new EncryptedWriteRequest(request, messageEncrypted));
        }
    } else {
        log.trace("Non-encrypted message");
        nextFilter.filterWrite(session, request);
    }
}
 
Example 16
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 17
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 18
Source File: Zlib.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Uncompress the given buffer, returning it in a new buffer.
 * 
 * @param inBuffer the {@link IoBuffer} to be decompressed. The contents
 * of the buffer are transferred into a local byte array and the buffer is
 * flipped and returned intact.
 * @return the decompressed data
 * @throws IOException if the decompression of the data failed for some reason.
 * @throws IllegalArgumentException if the mode is not <code>MODE_DEFLATER</code>
 */
public IoBuffer inflate(IoBuffer inBuffer) throws IOException {
    if (mode == MODE_DEFLATER) {
        throw new IllegalStateException("not initialized as INFLATER");
    }

    byte[] inBytes = new byte[inBuffer.remaining()];
    inBuffer.get(inBytes).flip();

    // We could probably do this better, if we're willing to return multiple buffers
    // (e.g. with a callback function)
    byte[] outBytes = new byte[inBytes.length * 2];
    IoBuffer outBuffer = IoBuffer.allocate(outBytes.length);
    outBuffer.setAutoExpand(true);

    synchronized (zStream) {
        zStream.next_in = inBytes;
        zStream.next_in_index = 0;
        zStream.avail_in = inBytes.length;
        zStream.next_out = outBytes;
        zStream.next_out_index = 0;
        zStream.avail_out = outBytes.length;
        int retval = 0;

        do {
            retval = zStream.inflate(JZlib.Z_SYNC_FLUSH);
            switch (retval) {
            case JZlib.Z_OK:
                // completed decompression, lets copy data and get out
            case JZlib.Z_BUF_ERROR:
                // need more space for output. store current output and get more
                outBuffer.put(outBytes, 0, zStream.next_out_index);
                zStream.next_out_index = 0;
                zStream.avail_out = outBytes.length;
                break;
            default:
                // unknown error
                outBuffer = null;
                if (zStream.msg == null) {
                    throw new IOException("Unknown error. Error code : " + retval);
                } else {
                    throw new IOException("Unknown error. Error code : " + retval + " and message : " + zStream.msg);
                }
            }
        } while (zStream.avail_in > 0);
    }

    return outBuffer.flip();
}
 
Example 19
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 ();
    }
}
 
Example 20
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);
    }
}