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

The following examples show how to use org.apache.mina.core.buffer.IoBuffer#mark() . 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: 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 2
Source File: ByteArrayFieldTypeHandler.java    From CXTouch with GNU General Public License v3.0 6 votes vote down vote up
@Override
public byte[] decode(IoBuffer inBuffer) {
    if (inBuffer.remaining() < 4) {
        return null;
    }
    inBuffer.mark();
    int length = inBuffer.getInt();
    if (inBuffer.remaining() < length) {
        inBuffer.reset();
        return null;
    }
    byte[] bytes = new byte[length];
    inBuffer.get(bytes);

    return bytes;
}
 
Example 3
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 4
Source File: VideoData.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
public void setData(IoBuffer data) {
    this.data = data;
    if (data != null && data.limit() > 0) {
        data.mark();
        int firstByte = data.get(0) & 0xff;
        codecId = firstByte & ITag.MASK_VIDEO_CODEC;
        if (codecId == VideoCodec.AVC.getId()) {
            int secondByte = data.get(1) & 0xff;
            config = (secondByte == 0);
            endOfSequence = (secondByte == 2);
        }
        data.reset();
        int frameType = (firstByte & MASK_VIDEO_FRAMETYPE) >> 4;
        if (frameType == FLAG_FRAMETYPE_KEYFRAME) {
            this.frameType = FrameType.KEYFRAME;
        } else if (frameType == FLAG_FRAMETYPE_INTERFRAME) {
            this.frameType = FrameType.INTERFRAME;
        } else if (frameType == FLAG_FRAMETYPE_DISPOSABLE) {
            this.frameType = FrameType.DISPOSABLE_INTERFRAME;
        } else {
            this.frameType = FrameType.UNKNOWN;
        }
    }
}
 
Example 5
Source File: MassProtocolDecoder.java    From game-server with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
protected boolean doDecode(IoSession session, IoBuffer ib, ProtocolDecoderOutput out) throws Exception {
    if (ib.remaining() < 4) {
        return false;
    }
    ib.mark();
    int length = ib.getInt();
    if (length < 1 || length > maxReadSize) {
        int id = ib.getInt();
        ib.clear();
        log.warn("消息解析异常:长度{},id {}, 大于长度 maxReadSize {}", length, id, maxReadSize);
        session.close(true);
        return false;
    }

    if (ib.remaining() < length) {
        ib.reset();
        return false;
    }
    decodeBytes(length, ib, out);
    return true;
}
 
Example 6
Source File: Packet.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
/**
 * Setter for data
 *
 * @param buffer
 *            Packet data
 */
public void setData(IoBuffer buffer) {
    if (noCopy) {
        log.trace("Using buffer reference");
        this.data = buffer;
    } else {
        // try the backing array first if it exists
        if (buffer.hasArray()) {
            log.trace("Buffer has backing array, making a copy");
            byte[] copy = new byte[buffer.limit()];
            buffer.mark();
            buffer.get(copy);
            buffer.reset();
            data = IoBuffer.wrap(copy);
        } else {
            log.trace("Buffer has no backing array, using ByteBuffer");
            // fallback to ByteBuffer
            data.put(buffer.buf()).flip();
        }
    }
}
 
Example 7
Source File: AudioData.java    From red5-server-common with Apache License 2.0 5 votes vote down vote up
public void setData(IoBuffer data) {
    if (data != null && data.limit() > 0) {
        data.mark();
        codecId = ((data.get(0) & 0xff) & ITag.MASK_SOUND_FORMAT) >> 4;
        if (codecId == AudioCodec.AAC.getId()) {
            config = (data.get() == 0);
        }
        data.reset();
    }
    this.data = data;
}
 
Example 8
Source File: WebMessageDecoder.java    From cim with Apache License 2.0 5 votes vote down vote up
private boolean isHandShakeRequest(IoSession iosession, IoBuffer buffer){
	if(Objects.equals(iosession.getAttribute(SOURCE),WEBSOCKET)) {
		return false;
	}

	buffer.mark();
	String data = new String(buffer.array());
	boolean handShake = getSecWebSocketKey(data) != null && Objects.equals(getUpgradeProtocol(data),WEBSOCKET);
	buffer.reset();
	return handShake;
}
 
Example 9
Source File: GameMsgDecoder.java    From TestClient with Apache License 2.0 5 votes vote down vote up
/**
 * flag(1 byte)+length(4 byte,后边内容的长度)+protocol code(4 byte)+content
 * length的长度包括  :消息号+ 内容
 */
@Override
protected boolean doDecode(IoSession session, IoBuffer iobuffer,
		ProtocolDecoderOutput protocolDecoderOutput) throws Exception {
	
	if(iobuffer.remaining()<(MsgProtocol.flagSize+MsgProtocol.lengthSize+MsgProtocol.msgCodeSize)){//数据不完整
		return false;
	}
	iobuffer.mark();
	byte flag = iobuffer.get();//flag,备用
	if (flag == 1) {
		int length = iobuffer.getInt();//读取长度字段
		if(length<=0 || length>MsgProtocol.maxPackLength){//长度字段异常
			return false;
		}
		if(iobuffer.remaining()>=length){//
			int preLimit = iobuffer.limit();//记录下当前的limit值
			iobuffer.limit(MsgProtocol.flagSize+MsgProtocol.lengthSize+length);
			byte[] body = new byte[length];
			iobuffer.get(body);
			iobuffer.limit(preLimit);
			Response message = new Response(body);
			protocolDecoderOutput.write(message);
			return true;
		}else{
			iobuffer.reset();
			return false;
		}
	}else{
		return false;
	}
}
 
Example 10
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 11
Source File: VmPipeFilterChain.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private Object getMessageCopy(Object message) {
    Object messageCopy = message;
    if (message instanceof IoBuffer) {
        IoBuffer rb = (IoBuffer) message;
        rb.mark();
        IoBuffer wb = IoBuffer.allocate(rb.remaining());
        wb.put(rb);
        wb.flip();
        rb.reset();
        messageCopy = wb;
    }
    return messageCopy;
}
 
Example 12
Source File: AudioData.java    From red5-server-common with Apache License 2.0 5 votes vote down vote up
/**
 * Create audio data event with given data buffer
 * 
 * @param data
 *            Audio data
 * @param copy
 *            true to use a copy of the data or false to use reference
 */
public AudioData(IoBuffer data, boolean copy) {
    super(Type.STREAM_DATA);
    if (copy) {
        byte[] array = new byte[data.remaining()];
        data.mark();
        data.get(array);
        data.reset();
        setData(array);
    } else {
        setData(data);
    }
}
 
Example 13
Source File: AppMessageDecoder.java    From cim with Apache License 2.0 5 votes vote down vote up
@Override
public void decode(IoSession session, IoBuffer iobuffer, ProtocolDecoderOutput out) throws Exception {
	

	if (iobuffer.remaining() < CIMConstant.DATA_HEADER_LENGTH) {
		return;
	}

	iobuffer.mark();

	byte type = iobuffer.get();
	byte lv = iobuffer.get();
	byte hv = iobuffer.get();

	int length = getContentLength(lv, hv);

	/*
	 *发生了断包情况如果消息体没有接收完整,则重置读取,等待下一次重新读取
	 */
	if (length > iobuffer.remaining()) {
		iobuffer.reset();
		return;
	}

	byte[] dataBytes = new byte[length];
	iobuffer.get(dataBytes, 0, length);

	Object message = mappingMessageObject(dataBytes, type);
	out.write(message);
}
 
Example 14
Source File: StringFieldTypeHandler.java    From CXTouch with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String decode(IoBuffer inBuffer) {
    if (inBuffer.remaining() < 4) {
        return null;
    }
    inBuffer.mark();
    int length = inBuffer.getInt();
    if (inBuffer.remaining() < length) {
        inBuffer.reset();
        return null;
    }
    byte[] bytes = new byte[length];
    inBuffer.get(bytes);
    return new String(bytes, 0, length, MessageUtil.CHARSET_UTF8);
}
 
Example 15
Source File: WebMessageDecoder.java    From cim with Apache License 2.0 4 votes vote down vote up
@Override
public void decode(IoSession iosession, IoBuffer in, ProtocolDecoderOutput out) throws InvalidProtocolBufferException{
	
	/*
	 * 判断是否是握手请求
	 */

	if(isHandShakeRequest(iosession,in)) {
		handleHandshake(iosession,in, out);
		return;
	}

	
	in.mark();
	
	/*
	 * 接下来判断fin标志位是否是1 如果是0 则等待消息接收完成
	 */
	byte tag = in.get();
	int frameFin = tag  > 0 ?  0 : 1;
	if(frameFin == 0) {
		in.reset();
		return;
	}
	
	/*
	 * 获取帧类型,因为使用了protobuf,所以只支持二进制帧 OPCODE_BINARY,以及客户端关闭连接帧通知 OPCODE_CLOSE
	 */
	int frameCode = tag & TAG_MASK;
	
	if(OPCODE_BINARY == frameCode) {
		
		byte head = in.get();
		byte dataLength = (byte) (head & PAYLOADLEN);
		int realLength;
		
		/*
		 *Payload len,7位或者7+16位或者7+64位,表示数据帧中数据大小,这里有好几种情况。
		 *如果值为0-125,那么该值就是payload data的真实长度。
		 *如果值为126,那么该7位后面紧跟着的2个字节就是payload data的真实长度。
		 *如果值为127,那么该7位后面紧跟着的8个字节就是payload data的真实长度。
		 */
		if (dataLength == HAS_EXTEND_DATA) {
			realLength = in.getShort();
		} else if (dataLength == HAS_EXTEND_DATA_CONTINUE) {
			realLength = (int) in.getLong();
		}else {
			realLength = dataLength;
		}

		boolean masked = (head >> 7 & MASK) == 1;
		if (masked) {
			byte[] mask = new byte[4];
			in.get(mask);
			
			byte[] data = new byte[realLength];
			in.get(data);
			for (int i = 0; i < realLength; i++) {
				data[i] = (byte) (data[i] ^ mask[i % 4]);
			}
			
			handleMessage(data,out);
		}
		
	}else if(OPCODE_CLOSE == frameCode) {
       	handleClose(iosession,in);
	}else {
		in.get(new byte[in.remaining()]);
	}

}
 
Example 16
Source File: MyDataDecoder.java    From QuickerAndroid with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 返回值含义:
 * 1、当内容刚好时,返回false,告知父类接收下一批内容
 * 2、内容不够时需要下一批发过来的内容,此时返回false,这样父类 CumulativeProtocolDecoder
 * 会将内容放进IoSession中,等下次来数据后就自动拼装再交给本类的doDecode
 * 3、当内容多时,返回true,因为需要再将本批数据进行读取,父类会将剩余的数据再次推送本类的doDecode方法
 */
@Override
public boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
        throws Exception {
    Log.d(TAG, "解码消息... len = " + in.remaining());

    /**
     * 假定消息格式为:消息头(int类型:表示消息体的长度、short类型:表示事件号)+消息体
     */
    if (in.remaining() < 12)
    {
        return false;
    }

        //以便后继的reset操作能恢复position位置
        in.mark();

        int headFlag = in.getInt();
        int msgType = in.getInt();
        int msgLength = in.getInt();

        if (  in.remaining() >= (msgLength + 4) ) {
            String msgJson = in.getString(msgLength, Charset.forName("UTF-8").newDecoder());
            int end = in.getInt();

            MessageBase msg = deserializeMsg(msgType, msgJson);
            out.write(msg);

            if (in.hasRemaining()) {
                return true;
            }else {
                return false;
            }
        }else {
            in.reset();

            // 消息不完整
            return false;
        }


}
 
Example 17
Source File: NTGCodec.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
public boolean decodable(IoSession session, IoBuffer inputBuffer)
{
	inputBuffer.order(ByteOrder.LITTLE_ENDIAN);

       boolean isDecodable = false;

       if(inputBuffer.remaining() < MINIMAL_CAPACITY) {
		return false;
	}

	inputBuffer.order(ByteOrder.LITTLE_ENDIAN);
	inputBuffer.mark();
	byte messageStartByte  = inputBuffer.get();

	// Implementation of SEVRER_START_OF_MESSAGE_INDICATOR need to be qualified.
       if(messageStartByte != CLIENT_START_OF_MESSAGE_INDICATOR
	/* && SEVRER_START_OF_MESSAGE_INDICATOR != messageStartByte */ )
	{
           inputBuffer.reset();

           logger.error("Unexpected start of message: {} (expected: {})", messageStartByte, CLIENT_START_OF_MESSAGE_INDICATOR);
           logger.error("Buffer hexdump:{}{}", System.lineSeparator(), HexDumper.getHexdump(inputBuffer, inputBuffer.remaining()));

           throw new EPSCommonException("Unexpected start of message: " + messageStartByte);
	}

       short messageLength = inputBuffer.getShort();

	if( messageLength < 0 )
	{
		throw new EPSCommonException( "Message length cannot be negative." );
	}

	if( inputBuffer.remaining() >= messageLength )
	{
		isDecodable = true;
	}

       byte messageType = inputBuffer.get();
	inputBuffer.reset();

	if(logger.isDebugEnabled())
	{
		messageLength += messageLength == 0 ? 0 : 3;
		logger.debug("decodable() result [{}].", isDecodable);
		logger.debug("decodable() message length [{}], message type [{}]", messageLength, messageType);
           //logger.debug( String.format(" decodable() as hex    [%s]", NTGUtility.getHexdump( inputBuffer, messageLength )));
		inputBuffer.reset();
		logger.debug(MINAUtil.getHexdumpAdv(inputBuffer, messageLength));
		inputBuffer.reset();
	}
	return isDecodable;
}
 
Example 18
Source File: RTMPProtocolDecoder.java    From red5-server-common with Apache License 2.0 4 votes vote down vote up
/**
 * Decode the 'action' for a supplied an Invoke.
 * 
 * @param encoding
 *            AMF encoding
 * @param in
 *            buffer
 * @param header
 *            data header
 * @return notify
 */
private Invoke decodeAction(Encoding encoding, IoBuffer in, Header header) {
    // for response, the action string and invokeId is always encoded as AMF0 we use the first byte to decide which encoding to use
    in.mark();
    byte tmp = in.get();
    in.reset();
    Input input;
    if (encoding == Encoding.AMF3 && tmp == AMF.TYPE_AMF3_OBJECT) {
        input = new org.red5.io.amf3.Input(in);
        ((org.red5.io.amf3.Input) input).enforceAMF3();
    } else {
        input = new org.red5.io.amf.Input(in);
    }
    // get the action
    String action = Deserializer.deserialize(input, String.class);
    if (action == null) {
        throw new RuntimeException("Action was null");
    }
    if (log.isTraceEnabled()) {
        log.trace("Action: {}", action);
    }
    // instance the invoke
    Invoke invoke = new Invoke();
    // set the transaction id
    invoke.setTransactionId(readTransactionId(input));
    // reset and decode parameters
    input.reset();
    // get / set the parameters if there any
    Object[] params = in.hasRemaining() ? handleParameters(in, invoke, input) : new Object[0];
    // determine service information
    final int dotIndex = action.lastIndexOf('.');
    String serviceName = (dotIndex == -1) ? null : action.substring(0, dotIndex);
    // pull off the prefixes since java doesn't allow this on a method name
    if (serviceName != null && (serviceName.startsWith("@") || serviceName.startsWith("|"))) {
        serviceName = serviceName.substring(1);
    }
    String serviceMethod = (dotIndex == -1) ? action : action.substring(dotIndex + 1, action.length());
    // pull off the prefixes since java doesnt allow this on a method name
    if (serviceMethod.startsWith("@") || serviceMethod.startsWith("|")) {
        serviceMethod = serviceMethod.substring(1);
    }
    // create the pending call for invoke
    PendingCall call = new PendingCall(serviceName, serviceMethod, params);
    invoke.setCall(call);
    return invoke;
}
 
Example 19
Source File: MessageUtil.java    From CXTouch with GNU General Public License v3.0 4 votes vote down vote up
public static String readString(IoBuffer buffer, LengthType lenType, CharsetDecoder decoder) throws NoArrayException {
    int length;
    int remain = buffer.remaining();
    buffer.mark();
    if (lenType == LengthType.INT) {
        if (remain < 4) {
            buffer.reset();
            throw new NoArrayException();
        }
        length = buffer.getInt();
    } else if(lenType == LengthType.SHORT) {
        if (remain < 2) {
            buffer.reset();
            throw new NoArrayException();
        }
        length = buffer.getShort();
    } else if (lenType == LengthType.BYTE) {
        if (remain < 1) {
            buffer.reset();
            throw new NoArrayException();
        }
        length = buffer.get();
    } else {
        buffer.reset();
        throw new IllegalArgumentException("Illegal type:" + lenType);
    }

    if (length < 0) {
        return null;
    } if (length == 0) {
        return "";
    } else {
        if (buffer.remaining() < length) {
            buffer.reset();
            throw new NoArrayException();
        }
        try {
            return buffer.getString(length, decoder);
        } catch (CharacterCodingException e) {
            throw new RuntimeException("Reading string failed:" + e.getMessage(), e);
        }
    }
}
 
Example 20
Source File: ITCHDeflateCodec.java    From sailfish-core with Apache License 2.0 2 votes vote down vote up
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {

	boolean debugEnabled = logger.isDebugEnabled();

	if(debugEnabled) {

		logger.debug("Decode [limit: {}; remaining: {}; buffer:\n{}]", in.limit(), in.remaining(),
		        MINAUtil.getHexdumpAdv( in, in.remaining()));
	}

	in.mark();
	in.order(ByteOrder.LITTLE_ENDIAN);

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

	byte[] actualDelimiter = new byte[DELIMITER_LENGTH];

	in.get(actualDelimiter);

	if(! Arrays.equals(delimiter, actualDelimiter)) {

           logger.error("Delimiter {} does not equeals to expected {}", actualDelimiter, delimiter);

	}

	int expectedDecompressedLength = in.getUnsignedShort();

	int chunkLength = in.getUnsignedShort();

	if (in.remaining() < chunkLength) {
		logger.debug("Received only part of bunch");
		in.reset();
		return false;
	}

	byte [] rawContent = new byte[(int)chunkLength];

	in.get(rawContent);

	byte[] decompressed = null;

	try {

		decompressed = decompress(rawContent);

	} catch (Exception e) {

		logger.error("Input could not be decompressed", e);
		return true;

	}

	if(debugEnabled) {

		logger.debug("Decompressed:\n{};", HexDumper.getHexdump(decompressed));

	}

	if(decompressed.length != expectedDecompressedLength) {
		logger.error("Lengs of the decompressed data {} is not equals to expected length {}",decompressed.length, expectedDecompressedLength);
	}

	IoBuffer buffer = IoBuffer.allocate(decompressed.length, false);

	buffer.put(decompressed);

	buffer.flip();

	out.write(buffer);

	return true;

}