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

The following examples show how to use org.apache.mina.core.buffer.IoBuffer#limit() . 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: RTMPMinaProtocolEncoder.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
public static int chunkAndWrite(ProtocolEncoderOutput out, IoBuffer message, int chunkSize, int desiredSize) {
    int sentChunks = 0;
    int targetSize = desiredSize > chunkSize ? desiredSize : chunkSize;
    int limit = message.limit();
    do {
        int length = 0;
        int pos = message.position();
        while (length < targetSize && pos < limit) {
            byte basicHeader = message.get(pos);
            length += getDataSize(basicHeader) + chunkSize;
            pos += length;
        }
        int remaining = message.remaining();
        log.trace("Length: {} remaining: {} pos+len: {} limit: {}", new Object[] { length, remaining, (message.position() + length), limit });
        if (length > remaining) {
            length = remaining;
        }
        // send it
        out.write(message.getSlice(length));
        sentChunks++;
    } while (message.hasRemaining());
    return sentChunks;
}
 
Example 2
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 3
Source File: ObjectSerializationInputStream.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
public Object readObject() throws ClassNotFoundException, IOException {
    int objectSize = in.readInt();
    if (objectSize <= 0) {
        throw new StreamCorruptedException("Invalid objectSize: " + objectSize);
    }
    if (objectSize > maxObjectSize) {
        throw new StreamCorruptedException("ObjectSize too big: " + objectSize + " (expected: <= " + maxObjectSize
                + ')');
    }

    IoBuffer buf = IoBuffer.allocate(objectSize + 4, false);
    buf.putInt(objectSize);
    in.readFully(buf.array(), 4, objectSize);
    buf.position(0);
    buf.limit(objectSize + 4);

    return buf.getObject(classLoader);
}
 
Example 4
Source File: BufferedWriteFilter.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Writes <code>data</code> {@link IoBuffer} to the <code>buf</code>
 * {@link IoBuffer} which buffers write requests for the
 * <code>session</code> {@ link IoSession} until buffer is full 
 * or manually flushed.
 * 
 * @param session the session where buffer will be written
 * @param data the data to buffer
 * @param buf the buffer where data will be temporarily written 
 */
private void write(IoSession session, IoBuffer data, IoBuffer buf) {
    try {
        int len = data.remaining();
        if (len >= buf.capacity()) {
            /*
             * If the request length exceeds the size of the output buffer,
             * flush the output buffer and then write the data directly.
             */
            NextFilter nextFilter = session.getFilterChain().getNextFilter(this);
            internalFlush(nextFilter, session, buf);
            nextFilter.filterWrite(session, new DefaultWriteRequest(data));
            return;
        }
        if (len > (buf.limit() - buf.position())) {
            internalFlush(session.getFilterChain().getNextFilter(this), session, buf);
        }
        synchronized (buf) {
            buf.put(data);
        }
    } catch (Throwable e) {
        session.getFilterChain().fireExceptionCaught(e);
    }
}
 
Example 5
Source File: M4AReader.java    From red5-io with Apache License 2.0 5 votes vote down vote up
/**
 * Create tag for metadata event.
 *
 * @return Metadata event tag
 */
ITag createFileMeta() {
    log.debug("Creating onMetaData");
    // Create tag for onMetaData event
    IoBuffer buf = IoBuffer.allocate(1024);
    buf.setAutoExpand(true);
    Output out = new Output(buf);
    out.writeString("onMetaData");
    Map<Object, Object> props = new HashMap<Object, Object>();
    // Duration property
    props.put("duration", ((double) duration / (double) timeScale));

    // Audio codec id - watch for mp3 instead of aac
    props.put("audiocodecid", audioCodecId);
    props.put("aacaot", audioCodecType);
    props.put("audiosamplerate", audioTimeScale);
    props.put("audiochannels", audioChannels);
    props.put("canSeekToEnd", false);
    out.writeMap(props);
    buf.flip();

    //now that all the meta properties are done, update the duration
    duration = Math.round(duration * 1000d);

    ITag result = new Tag(IoConstants.TYPE_METADATA, 0, buf.limit(), null, 0);
    result.setBody(buf);
    return result;
}
 
Example 6
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 7
Source File: SpeexAudio.java    From red5-io with Apache License 2.0 5 votes vote down vote up
@Override
public boolean canHandleData(IoBuffer data) {
    if (data.limit() == 0) {
        // Empty buffer
        return false;
    }
    byte first = data.get();
    boolean result = (((first & 0xf0) >> 4) == AudioCodec.SPEEX.getId());
    data.rewind();
    return result;
}
 
Example 8
Source File: StatusObjectService.java    From red5-server-common with Apache License 2.0 5 votes vote down vote up
/**
 * Cache status objects
 */
public void cacheStatusObjects() {

    cachedStatusObjects = new HashMap<String, byte[]>();

    String statusCode;
    IoBuffer out = IoBuffer.allocate(256);
    out.setAutoExpand(true);

    for (String s : statusObjects.keySet()) {
        statusCode = s;
        StatusObject statusObject = statusObjects.get(statusCode);
        if (statusObject instanceof RuntimeStatusObject) {
            continue;
        }
        serializeStatusObject(out, statusObject);
        out.flip();
        if (log.isTraceEnabled()) {
            log.trace(HexDump.formatHexDump(out.getHexDump()));
        }
        byte[] cachedBytes = new byte[out.limit()];
        out.get(cachedBytes);
        out.clear();
        cachedStatusObjects.put(statusCode, cachedBytes);
    }
    out.free();
    out = null;
}
 
Example 9
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 10
Source File: NioProcessor.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected int write(NioSession session, IoBuffer buf, int length) throws Exception {
    if (buf.remaining() <= length) {
        return session.getChannel().write(buf.buf());
    }

    int oldLimit = buf.limit();
    buf.limit(buf.position() + length);
    try {
        return session.getChannel().write(buf.buf());
    } finally {
        buf.limit(oldLimit);
    }
}
 
Example 11
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 12
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 13
Source File: ServerProtocolTCPDecoder.java    From seed with Apache License 2.0 5 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_TCP);
    token.setBusiCode(fullMessage.substring(6, 11));
    token.setBusiMessage(fullMessage);
    token.setFullMessage(fullMessage);
    out.write(token);
    return MessageDecoderResult.OK;
}
 
Example 14
Source File: MP3Audio.java    From red5-io with Apache License 2.0 5 votes vote down vote up
@Override
public boolean canHandleData(IoBuffer data) {
    if (data.limit() == 0) {
        // Empty buffer
        return false;
    }
    byte first = data.get();
    boolean result = (((first & 0xf0) >> 4) == AudioCodec.MP3.getId());
    data.rewind();
    return result;
}
 
Example 15
Source File: AACAudio.java    From red5-io with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public boolean canHandleData(IoBuffer data) {
    if (data.limit() == 0) {
        // Empty buffer
        return false;
    }
    byte first = data.get();
    boolean result = (((first & 0xf0) >> 4) == AudioCodec.AAC.getId());
    data.rewind();
    return result;
}
 
Example 16
Source File: SorensonVideo.java    From red5-io with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public boolean canHandleData(IoBuffer data) {
    if (data.limit() > 0) {
        byte first = data.get();
        data.rewind();
        return ((first & 0x0f) == VideoCodec.H263.getId());
    }
    return false;
}
 
Example 17
Source File: SorensonVideo.java    From red5-io with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public boolean addData(IoBuffer data) {
    if (data.limit() == 0) {
        return true;
    }
    if (!this.canHandleData(data)) {
        return false;
    }
    byte first = data.get();
    //log.trace("First byte: {}", HexDump.toHexString(first));
    data.rewind();
    // get frame type
    int frameType = (first & MASK_VIDEO_FRAMETYPE) >> 4;
    if (frameType != FLAG_FRAMETYPE_KEYFRAME) {
        // Not a keyframe
        try {
            int lastInterframe = numInterframes.getAndIncrement();
            if (frameType != FLAG_FRAMETYPE_DISPOSABLE) {
                log.trace("Buffering interframe #{}", lastInterframe);
                if (lastInterframe < interframes.size()) {
                    interframes.get(lastInterframe).setData(data);
                } else {
                    interframes.add(new FrameData(data));
                }
            } else {
                numInterframes.set(lastInterframe);
            }
        } catch (Throwable e) {
            log.error("Failed to buffer interframe", e);
        }
        data.rewind();
        return true;
    }
    numInterframes.set(0);
    interframes.clear();
    // Store last keyframe
    dataCount = data.limit();
    if (blockSize < dataCount) {
        blockSize = dataCount;
        blockData = new byte[blockSize];
    }
    data.get(blockData, 0, dataCount);
    data.rewind();
    return true;
}
 
Example 18
Source File: IoBufferDecoder.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Will return null unless it has enough data to decode. If <code>contentLength</code>
 * is set then it tries to retrieve <code>contentLength</code> bytes from the buffer
 * otherwise it will scan the buffer to find the data <code>delimiter</code> and return
 * all the data and the trailing delimiter.
 * 
 * @param in the data to decode
 */
public IoBuffer decodeFully(IoBuffer in) {
    int contentLength = ctx.getContentLength();
    IoBuffer decodedBuffer = ctx.getDecodedBuffer();

    int oldLimit = in.limit();

    // Retrieve fixed length content
    if (contentLength > -1) {
        if (decodedBuffer == null) {
            decodedBuffer = IoBuffer.allocate(contentLength).setAutoExpand(true);
        }

        // If not enough data to complete the decoding
        if (in.remaining() < contentLength) {
            int readBytes = in.remaining();
            decodedBuffer.put(in);
            ctx.setDecodedBuffer(decodedBuffer);
            ctx.setContentLength(contentLength - readBytes);
            return null;

        }

        int newLimit = in.position() + contentLength;
        in.limit(newLimit);
        decodedBuffer.put(in);
        decodedBuffer.flip();
        in.limit(oldLimit);
        ctx.reset();

        return decodedBuffer;
    }

    // Not a fixed length matching so try to find a delimiter match
    int oldPos = in.position();
    int matchCount = ctx.getMatchCount();
    IoBuffer delimiter = ctx.getDelimiter();

    while (in.hasRemaining()) {
        byte b = in.get();
        if (delimiter.get(matchCount) == b) {
            matchCount++;
            if (matchCount == delimiter.limit()) {
                // Found a match.
                int pos = in.position();
                in.position(oldPos);

                in.limit(pos);

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

                decodedBuffer.put(in);
                decodedBuffer.flip();

                in.limit(oldLimit);
                ctx.reset();

                return decodedBuffer;
            }
        } else {
            in.position(Math.max(0, in.position() - matchCount));
            matchCount = 0;
        }
    }

    // Copy remainder from buf.
    if (in.remaining() > 0) {
        in.position(oldPos);
        decodedBuffer.put(in);
        in.position(in.limit());
    }

    // Save decoding state
    ctx.setMatchCount(matchCount);
    ctx.setDecodedBuffer(decodedBuffer);

    return decodedBuffer;
}
 
Example 19
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 20
Source File: ServerProtocolHTTPDecoder.java    From seed with Apache License 2.0 4 votes vote down vote up
/**
 * 校验HTTP请求报文是否已完整接收
 * 目前仅授理GET和POST请求
 * ----------------------------------------------------------------------------------------------
 * GET /notify_yeepay?p1_MerId=11&r0_Cmd=Buy&r1_Code=1&r2_TrxId=22 HTTP/1.1^M
 * Content-Type: application/x-www-form-urlencoded; charset=GBK^M
 * Cache-Control: no-cache^M
 * Pragma: no-cache^M
 * User-Agent: Java/1.5.0_14^M
 * Host: 123.125.97.248^M
 * Accept: text/html, image/gif, image/jpeg, *; q=.2, 星号/*; q=.2^M
 * Connection: keep-alive^M
 * ^M
 * ----------------------------------------------------------------------------------------------
 * POST /tra/trade/noCardNoPassword.htm HTTP/1.1^M
 * Content-Type: application/x-www-form-urlencoded;charset=GB18030^M
 * Cache-Control: no-cache^M
 * Pragma: no-cache^M
 * User-Agent: Java/1.6.0_24^M
 * Host: 192.168.20.1^M
 * Accept: text/html, image/gif, image/jpeg, *; q=.2, 星号/*; q=.2^M
 * Connection: keep-alive^M
 * Content-Length: 541^M
 * ^M
 * cooBankNo=CMBC_CREDIT&signType=MD5&amount=499900&orderValidityNum=15&CVVNo=255
 * ----------------------------------------------------------------------------------------------
 * 至于上面所列的GET和POST请求原始报文中为何会出现^M
 * 我的博客上有详细说明:https://jadyer.cn/2012/11/22/linux-crlf/
 * ----------------------------------------------------------------------------------------------
 * @param in 装载HTTP请求报文的IoBuffer
 */
private boolean isComplete(IoBuffer in){
    /*
     * 先获取HTTP请求的原始报文
     */
    byte[] messages = new byte[in.limit()];
    in.get(messages);
    String message = StringUtils.toEncodedString(messages, Charset.forName(SeedConstants.DEFAULT_CHARSET));
    /*
     * 授理GET请求
     */
    if(message.startsWith("GET")){
        return message.endsWith("\r\n\r\n");
    }
    /*
     * 授理POST请求
     */
    if(message.startsWith("POST")){
        if(message.contains("Content-Length:")){
            //取Content-Length后的字符串
            String msgLenFlag = message.substring(message.indexOf("Content-Length:") + 15);
            if(msgLenFlag.contains("\r\n")){
                //取Content-Length值
                int contentLength = Integer.parseInt(msgLenFlag.substring(0, msgLenFlag.indexOf("\r\n")).trim());
                if(contentLength == 0){
                    return true;
                }else if(contentLength >= 0){
                    //取HTTP_POST请求报文体
                    String messageBody = message.split("\r\n\r\n")[1];
                    try {
                        if(contentLength == messageBody.getBytes(SeedConstants.DEFAULT_CHARSET).length){
                            return true;
                        }
                    } catch (UnsupportedEncodingException e) {
                        throw new IllegalArgumentException("将HTTP_POST请求报文体转为byte[]时发生异常:Unsupported Encoding-->[" + SeedConstants.DEFAULT_CHARSET + "]");
                    }
                }
            }
        }
    }
    /*
     * 仅授理GET和POST请求
     */
    return false;
}