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

The following examples show how to use org.apache.mina.core.buffer.IoBuffer#reset() . 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: 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 2
Source File: HttpServerDecoderImpl.java    From game-server with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
protected boolean doDecode(IoSession session, IoBuffer msg, ProtocolDecoderOutput out) throws Exception {
	/**
	 * 消息已经解析
	 * 谷歌浏览器一次请求存在多次收到消息,还额外请求了/favicon.ico路径
	 */
	if (session.containsAttribute(HTTP_REQUEST)) {
		return false;
	}
	msg.mark();
	HttpRequestImpl rq = parseHttpRequestHead(msg.buf(), msg);
	if (rq != null) {
		out.write(rq);
		session.setAttribute(HTTP_REQUEST, rq);
		// LOG.info("解析成功");
		return true;
	}
	msg.reset();
	return false;
}
 
Example 3
Source File: Aggregate.java    From red5-server-common with Apache License 2.0 5 votes vote down vote up
/**
 * Create aggregate data event with given data buffer.
 * 
 * @param data
 *            aggregate data
 * @param copy
 *            true to use a copy of the data or false to use reference
 */
public Aggregate(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 4
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 5
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 6
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 7
Source File: AbstractPollingIoProcessor.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private int writeBuffer(S session, WriteRequest req, boolean hasFragmentation, int maxLength, long currentTime)
        throws Exception {
    IoBuffer buf = (IoBuffer) req.getMessage();
    int localWrittenBytes = 0;

    if (buf.hasRemaining()) {
        int length;

        if (hasFragmentation) {
            length = Math.min(buf.remaining(), maxLength);
        } else {
            length = buf.remaining();
        }

        try {
            localWrittenBytes = write(session, buf, length);
        } catch (IOException ioe) {
            // We have had an issue while trying to send data to the 
            // peer : let's close the session.
            session.close(true);
        }

    }

    session.increaseWrittenBytes(localWrittenBytes, currentTime);

    if (!buf.hasRemaining() || (!hasFragmentation && (localWrittenBytes != 0))) {
        // Buffer has been sent, clear the current request.
        int pos = buf.position();
        buf.reset();

        fireMessageSent(session, req);

        // And set it back to its position
        buf.position(pos);
    }

    return localWrittenBytes;
}
 
Example 8
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 9
Source File: VideoData.java    From red5-server-common with Apache License 2.0 5 votes vote down vote up
/**
 * Create video data event with given data buffer
 * 
 * @param data
 *            Video data
 * @param copy
 *            true to use a copy of the data or false to use reference
 */
public VideoData(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 10
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 11
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 12
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 13
Source File: NTGCodec.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
@Override
public boolean doDecode(IoSession session, IoBuffer inputBuffer, ProtocolDecoderOutput pdOutput) throws Exception
{
	if ( !decodable(session, inputBuffer) ) {
		return false;
	}

	boolean resultDecode = false;
	inputBuffer.order(ByteOrder.LITTLE_ENDIAN);
	inputBuffer.mark();
	inputBuffer.position(inputBuffer.markValue() + MINIMAL_CAPACITY - 1);
	byte messageType = inputBuffer.get();
	inputBuffer.reset();
	int startposition = inputBuffer.position();

       IMessageStructure msgStructure = decodeMsgTypeToStructure.get(messageType);

       if(msgStructure == null) {
		throw new UndefinedMessageException("Message type ["+messageType+"] is not defined in the dictionary.");
	}

	IMessage msg = msgFactory.createMessage(msgStructure.getName(), msgStructure.getNamespace());
       NTGVisitorDecode visitorNTGDecode = new NTGVisitorDecode(inputBuffer, msgFactory, msg);
       MessageStructureWriter.WRITER.traverse(visitorNTGDecode, msgStructure);
       IMessage msgDecoded = visitorNTGDecode.getMessage();

       if(msgDecoded != null)
	{
           pdOutput.write(visitorNTGDecode.getMessage());
		resultDecode = true;
	}
	else
	{
		resultDecode = false;
	}

	int sizeofmessage = inputBuffer.position();
	sizeofmessage -= startposition;
	byte[] rawMsg = new byte[sizeofmessage];
	System.arraycopy( inputBuffer.array(), startposition, rawMsg, 0, sizeofmessage );
       if(msgDecoded != null) {
		msgDecoded.getMetaData().setRawMessage( rawMsg );
	}

	return resultDecode;
}
 
Example 14
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 15
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 16
Source File: InternalJsonCodec.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    boolean decoded = false;

    while (in.remaining() > HEADER_SIZE) {
        in.mark();
        long length = in.getLong();
        long seq = in.getLong();

        if (in.remaining() >= length) {
            byte[] buff = new byte[(int) length];
            in.get(buff);

            if (logger.isDebugEnabled()) {
                logger.debug("decode() sequnce {} as hex [{}]", seq, Hex.encodeHex(buff));
            }
            decoded = true;

            in.reset();
            byte[] rawData = new byte[(int) length + HEADER_SIZE];
            in.get(rawData);

            IMessage message = null;

            try {
                Map<?, ?> map = objectMapper.readValue(buff, HashMap.class);
                message = MessageUtil.convertToIMessage(map, msgFactory, TCPIPMessageHelper.INCOMING_MESSAGE_NAME_AND_NAMESPACE,
                        TCPIPMessageHelper.INCOMING_MESSAGE_NAME_AND_NAMESPACE);

            } catch (Exception e) {
                message = msgFactory.createMessage("Exception",
                        TCPIPMessageHelper.INCOMING_MESSAGE_NAME_AND_NAMESPACE);

                message.addField("Cause", e.getMessage());
            }

            message.getMetaData().setRawMessage(rawData);
            out.write(message);
        } else {
            in.reset();
        }
    }

    return decoded;
}
 
Example 17
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 18
Source File: GameMsgDecoder.java    From GameServer with Apache License 2.0 4 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)){//数据不完整
		logger.info("数据包长度不足");
		return false;
	}
	iobuffer.mark();
	byte flag = iobuffer.get();//flag,备用
	if (flag == 1) {
		int length = iobuffer.getInt();//读取长度字段
		if(length<=0 || length>MsgProtocol.maxPackLength){//长度字段异常
			logger.info("数据包长度异常");
			return false;
		}
		if(iobuffer.remaining()>=length){//
			int preLimit = iobuffer.limit();//记录下当前的limit值
			
			/**
			 * 这行代码有一个bug,
			 * 读取协议内容时,如果第一个字节不是1,则越过此字节继续往后的读,直到读到1,
			 * 然而在设置limit时没有考虑到越过去的flag之前的字节,从而导致设置的limit比本应设置的位置小。
			 * 所以导致,iobuffer中当前position到设置的limit的长度小于我们要读取的length。
			 * 结果导致抛出BufferUnderflowException
			 */
			//iobuffer.limit(MsgProtocol.flagSize+MsgProtocol.lengthSize+length);
			iobuffer.limit(iobuffer.position()+length);
			byte[] body = new byte[length];
			iobuffer.get(body);
			iobuffer.limit(preLimit);
			ClientRequest message = new ClientRequest(body);
			protocolDecoderOutput.write(message);
			return true;
		}else{
			logger.info("数据包尚不完整");
			iobuffer.reset();
			return false;
		}
	}else{
		logger.info("flag 错误");
		return false;
	}
}
 
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;

}