@Override protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { final Pack pack = getPack(session); if (!pack.headDone) { if (in.remaining() < 8) { return false; } else { int code = in.getInt(); int len = in.getInt(); pack.setHead(code, len); } } int requires = pack.requires(); int remains = in.remaining(); int cpyLen = Math.min(requires, remains); pack.readBytes(in, cpyLen); requires = pack.requires(); if (requires == 0) { out.write(pack.toMsg()); pack.reset(); return true; } return false; }
/** * {@inheritDoc} */ @Override public void decode( IoSession session, IoBuffer in, ProtocolDecoderOutput out ) throws Exception { @SuppressWarnings("unchecked") LdapMessageContainer<MessageDecorator<? extends Message>> messageContainer = ( LdapMessageContainer<MessageDecorator<? extends Message>> ) session.getAttribute( LdapDecoder.MESSAGE_CONTAINER_ATTR ); if ( session.containsAttribute( LdapDecoder.MAX_PDU_SIZE_ATTR ) ) { int maxPDUSize = ( Integer ) session.getAttribute( LdapDecoder.MAX_PDU_SIZE_ATTR ); messageContainer.setMaxPDUSize( maxPDUSize ); } List<Message> decodedMessages = new ArrayList<>(); ByteBuffer buf = in.buf(); decode( buf, messageContainer, decodedMessages ); for ( Message message : decodedMessages ) { out.write( message ); } }
@Override public synchronized void decode ( final IoSession session, final IoBuffer in, final ProtocolDecoderOutput out ) throws Exception { IoBuffer currentFrame = (IoBuffer)session.getAttribute ( SESSION_KEY_CURRENT_FRAME ); if ( currentFrame == null ) { currentFrame = IoBuffer.allocate ( Constants.MAX_PDU_SIZE + Constants.RTU_HEADER_SIZE ); session.setAttribute ( SESSION_KEY_CURRENT_FRAME, currentFrame ); } logger.trace ( "decode () current frame = {} data = {}", currentFrame.toString (), currentFrame.getHexDump () ); logger.trace ( "decode () new frame = {} data = {}", in.toString (), in.getHexDump () ); final int expectedSize = currentFrame.position () + in.remaining (); if ( expectedSize > MAX_SIZE + 1 ) { throw new ModbusProtocolError ( String.format ( "received size (%s) exceeds max size (%s)", expectedSize, MAX_SIZE ) ); } currentFrame.put ( in ); tick ( session, out ); }
@Override public void decode ( final IoSession session, final IoBuffer data, final ProtocolDecoderOutput output ) throws Exception { final short magic = data.getShort (); final byte version = data.get (); final int sequence = data.getInt (); final byte commandCode = data.get (); if ( magic != 1202 ) { throw new ProtocolCodecException ( String.format ( "Magic code should be 1202 but is %s", magic ) ); } if ( version != 1 ) { throw new ProtocolCodecException ( String.format ( "Version should be %s but is %s", 1, version ) ); } decodeMessage ( sequence, commandCode, data, output ); }
private void wrapTimeout ( final IoSession session, final ProtocolDecoderOutput out ) { try { timeout ( session, out ); } catch ( final Throwable e ) { try { session.getHandler ().exceptionCaught ( session, e ); } catch ( final Throwable ee ) { logger.warn ( "Exception was thrown during handling Exception", ee ); } } }
public synchronized void check () { if ( this.disposed ) { return; } if ( this.lastData == null ) { return; } if ( System.currentTimeMillis () - this.lastData > this.timeout ) { final ProtocolDecoderOutput out = this.out; TimedEndDecoder.this.clear ( this.session ); this.decoder.wrapTimeout ( this.session, out ); } }
/** * {@inheritDoc} */ public DecodingState decode(IoBuffer in, ProtocolDecoderOutput out) throws Exception { while (in.hasRemaining()) { switch (counter) { case 0: firstByte = in.getUnsigned(); break; case 1: secondByte = in.getUnsigned(); break; case 2: thirdByte = in.getUnsigned(); break; case 3: counter = 0; return finishDecode((firstByte << 24) | (secondByte << 16) | (thirdByte << 8) | in.getUnsigned(), out); default: throw new InternalError(); } counter++; } return this; }
/** * {@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; }
/** * {@inheritDoc} */ public DecodingState decode(IoBuffer in, ProtocolDecoderOutput out) throws Exception { while (in.hasRemaining()) { switch (counter) { case 0: highByte = in.getUnsigned(); break; case 1: counter = 0; return finishDecode((short) ((highByte << 8) | in.getUnsigned()), out); default: throw new InternalError(); } counter++; } return this; }
private boolean processWriteCommand ( final IoSession session, final IoBuffer data, final ProtocolDecoderOutput out ) throws ProtocolCodecException { final int len = messageLength ( data ); if ( len < 0 ) { return false; } final int registerNumber = data.getUnsignedShort (); final int operationId = data.getInt (); final Variant value = decodeVariant ( session, data ); out.write ( new WriteCommand ( registerNumber, value, operationId ) ); return true; }
private boolean processWriteResult ( final IoSession session, final IoBuffer data, final ProtocolDecoderOutput out ) throws ProtocolCodecException { final int len = messageLength ( data ); if ( len < 0 ) { return false; } try { final int operationId = data.getInt (); final int errorCode = data.getUnsignedShort (); final String errorMessage = decodeString ( session, data ); out.write ( new WriteResult ( operationId, errorCode, errorMessage ) ); } catch ( final CharacterCodingException e ) { throw new ProtocolCodecException ( e ); } return true; }
private boolean processDataUpdate ( final IoSession session, final IoBuffer data, final ProtocolDecoderOutput out ) throws ProtocolCodecException { final int len = messageLength ( data ); if ( len < 0 ) { return false; } final int count = data.getUnsignedShort (); final List<DataUpdate.Entry> entries = new ArrayList<DataUpdate.Entry> ( count ); for ( int i = 0; i < count; i++ ) { entries.add ( decodeDataUpdateEntry ( data, session ) ); } out.write ( new DataUpdate ( entries ) ); return true; }
private boolean processBrowseAdded ( final IoSession session, final IoBuffer data, final ProtocolDecoderOutput out ) throws ProtocolCodecException { final int len = messageLength ( data ); if ( len < 0 ) { return false; } final int count = data.getUnsignedShort (); final List<BrowseAdded.Entry> entries = new ArrayList<BrowseAdded.Entry> ( count ); for ( int i = 0; i < count; i++ ) { entries.add ( decodeBrowserAddEntry ( data, session ) ); } out.write ( new BrowseAdded ( entries ) ); return true; }
private boolean processHello ( final IoSession session, final IoBuffer data, final ProtocolDecoderOutput out ) throws ProtocolCodecException { final int len = messageLength ( data ); if ( len < 0 ) { return false; } final byte version = data.get (); if ( version != 0x01 ) { throw new ProtocolCodecException ( String.format ( "Protocol version %s is unsupported", version ) ); } final short nodeId = data.getShort (); final EnumSet<Hello.Features> features = data.getEnumSetShort ( Hello.Features.class ); out.write ( new Hello ( nodeId, features ) ); return true; }
private void wrapTimeout ( final IoSession session, final ProtocolDecoderOutput out ) { try { timeout ( session, out ); } catch ( final Throwable e ) { try { session.getHandler ().exceptionCaught ( session, e ); } catch ( final Throwable ee ) { LOGGER.warn ( "Exception was thrown during handling Exception", ee ); } } }
public synchronized void check () { if ( this.disposed ) { return; } if ( this.lastData == null ) { return; } if ( System.currentTimeMillis () - this.lastData > this.timeout ) { final ProtocolDecoderOutput out = this.out; clear (); this.decoder.wrapTimeout ( this.session, out ); } }
@Override protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { if (in.prefixedDataAvailable(2)) { short length = in.getShort();//获取包长 byte[] bytes = new byte[length]; in.get(bytes); byte[] msgidBytes = new byte[Constants.COMMAND_LENGTH]; System.arraycopy(bytes, 0, msgidBytes, 0, Constants.COMMAND_LENGTH); int msgid = NumberUtils.bytesToInt(msgidBytes); if (msgid != 0) { //通过工厂方法生成指定消息类型的指令对象 BaseCommand command = CommandFactory.createCommand(msgid); byte[] cmdBodyBytes = new byte[length - Constants.COMMAND_LENGTH]; System.arraycopy(bytes, Constants.COMMAND_LENGTH, cmdBodyBytes, 0, length - Constants.COMMAND_LENGTH); command.bodyFromBytes(cmdBodyBytes); out.write(command); return true; } } return false; }
@Override public boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { // log.debug("doDecode(...)..."); XMLLightweightParser parser = (XMLLightweightParser) session .getAttribute(XmppIoHandler.XML_PARSER); parser.read(in); // 如果有消息 if (parser.areThereMsgs()) { for (String stanza : parser.getMsgs()) { out.write(stanza); } } // 是否还有剩余 return !in.hasRemaining(); }
@Override public ProtocolDecoder getDecoder(IoSession is) throws Exception { return new CumulativeProtocolDecoder() { protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { if (in.remaining() > 0) { byte[] buf = new byte[in.remaining()]; in.get(buf); out.write(new String(buf, "US-ASCII")); return true; } else { return false; } } }; }
@Override public void decode(IoSession ioSession, IoBuffer ioBuffer, ProtocolDecoderOutput out) throws Exception { byte[] message = new byte[ioBuffer.limit()]; ioBuffer.get(message); UltravoxMessage ultravoxMessage = UltravoxMessageFactory.getMessage(message); if(ultravoxMessage != null) { out.write(ultravoxMessage); } else { out.write(message); } }
@Override protected boolean doDecode(IoSession is, IoBuffer ib, ProtocolDecoderOutput pdo) throws Exception { synchronized (is) { final MessageCodec stats = getSessionCodec(is); // 消息 SessionMessage message = null; // 消息不等于空,循环读取消息 do { message = stats.readMessage(is, ib); if (message != null) { pdo.write(message); } } while (message != null); // 调试输出 // System.out.println(ib); return message != null; } }
@Override protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { RedisProtocolParser parser = (RedisProtocolParser) session.getAttribute(REDIS_PROTOCOL_PARSER); // 将接收到的数据通过解析器解析为Redis数据包对象 parser.read(in.buf()); // 获取解析器解析出的数据包 RedisPacket[] redisPackets = parser.getPackets(); if (redisPackets != null) { for (RedisPacket redisPacket : redisPackets) { out.write(redisPacket); } } // 以是否读取完数据为判断符 return !in.hasRemaining(); }
@Override protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { if (in.remaining() < 4) { return false; } in.mark(); // mark 2 reset, reset call rollback to mark place int dataLength = in.getInt(); // data length if (dataLength < in.remaining()) { return false; } if (dataLength > in.remaining()) { in.reset(); } byte[] datas = new byte[dataLength]; // data in.get(datas, 0, dataLength); Object obj = serializer.deserialize(datas, genericClass); out.write(obj); return true; }
public MessageDecoderResult decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws ProtocolCodecException { int messageCount = 0; while (parseMessage(in, out)) { messageCount++; } if (messageCount > 0) { // Mina will compact the buffer because we can't detect a header if (in.remaining() < HEADER_PATTERN.length) { position = 0; } return MessageDecoderResult.OK; } else { // Mina will compact the buffer position -= in.position(); return MessageDecoderResult.NEED_DATA; } }
/** * Utility to extract messages from a file. This method will return each * message found to a provided listener. The message file will also be * memory mapped rather than fully loaded into physical memory. Therefore, * a large message file can be processed without using excessive memory. * * @param file * @param listener * @throws IOException * @throws ProtocolCodecException */ public void extractMessages(File file, final MessageListener listener) throws IOException, ProtocolCodecException { // Set up a read-only memory-mapped file FileChannel readOnlyChannel = new RandomAccessFile(file, "r").getChannel(); MappedByteBuffer memoryMappedBuffer = readOnlyChannel.map(FileChannel.MapMode.READ_ONLY, 0, (int) readOnlyChannel.size()); decode(null, ByteBuffer.wrap(memoryMappedBuffer), new ProtocolDecoderOutput() { public void write(Object message) { listener.onMessage((String) message); } public void flush() { // ignored } }); }
/** * 解码并处理断包 */ @Override public MessageDecoderResult decode(IoSession session, IoBuffer buffer, ProtocolDecoderOutput output) throws Exception { int nRemainning = buffer.remaining(); if (nRemainning < MessageCodec.HEAD_LENGTH) {// min length return MessageDecoderResult.NEED_DATA; } else { buffer.mark();// 标记位置mark=pos int nLen = buffer.getShort();// 包长(包括消息头) buffer.reset();// 重置位置pos=mark // 如果buffer中可读的长度小于包长说明断包返回 NEED_DATA if (nRemainning < nLen) { // buffer.reset();//重置位置pos=mark return MessageDecoderResult.NEED_DATA; } // buffer.reset();//重置位置pos=mark } Object proObj = decodeBody(session, buffer); output.write(proObj);// 解码后输出 return MessageDecoderResult.OK; }
private boolean doDecode(IoSession session, IoBuffer buffer,ProtocolDecoderOutput out) throws Exception { if(buffer.remaining() < 8){ //<=8 return false; } byte[] tmp = new byte[8]; buffer.get(tmp); ByteBuffer bytebuffer = ByteBuffer.wrap(tmp); bytebuffer.order(ByteOrder.LITTLE_ENDIAN); bytebuffer.getInt(); int dataLen = bytebuffer.getInt(); buffer.position(buffer.position()-8);//读取包括数据长度的信息 //数据体长度有效时 if(buffer.remaining()>=dataLen){ byte[] b = new byte[dataLen]; buffer.get(b); out.write(b); return true; } return false; }
@Override protected final boolean doDecode(IoSession session, IoBuffer buf, ProtocolDecoderOutput out) throws Exception { /*byte cmd = buf.get(); byte error = buf.get(); byte b1 = buf.get(); byte b2 = buf.get(); short packetLength = (short) (b2 & 0xFF << 8 | b1 & 0xFF); int length = buf.remaining(); if (packetLength >= length) { byte[] in = new byte[packetLength + 4]; in[0] = cmd; in[1] = error; in[2] = b1; in[3] = b2; buf.get(in, 4, packetLength); out.write(in); return true; } return false;*/ int length = buf.remaining(); byte[] input = new byte[length]; buf.get(input, 0, length); out.write(input); return true; }
protected void doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out, int pack, int length) { byte[] result = new byte[0]; int limit = in.limit(); byte[] bodyBytes = new byte[limit]; in.get(bodyBytes); in.position(limit); // byte[] headBytes = ByteHelper.toByteArray(pack); byte[] lengthBytes = ByteHelper.toByteArray(length); // // result = ArrayHelper.add(headBytes, lengthBytes); // result = ArrayHelper.add(result, bodyBytes); result = headBytes; result = UnsafeHelper.putByteArray(result, result.length, lengthBytes); result = UnsafeHelper .putByteArray(result, result.length, bodyBytes); // out.write(result); }
/** * Decode the RpcRequest */ protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { if (in.prefixedDataAvailable(HEADER_LENGTH, MAX_LENGTH)) { RpcMessage.Builder rpcRequestBuilder = RpcMessage.newBuilder(); int length = in.getInt(); byte[] bytes = new byte[length]; in.get(bytes); rpcRequestBuilder.mergeFrom(bytes); out.write(rpcRequestBuilder.build()); return true; } else { // not enough data available return false; } }
/** * Decode the message. */ @Override protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { // XinqiMessage message = (XinqiMessage) session.getAttribute(DECODER_STATE_KEY); // if ( message == null ) { // message = new XinqiMessage(); // session.setAttribute(DECODER_STATE_KEY, message); // } Object obj = ProtobufDecoder.decodeXinqiMessage(in); if ( obj instanceof XinqiMessage ) { XinqiMessage message = (XinqiMessage)obj; if ( message == null ) { return false; } out.write(message); return true; } // session.setAttribute(DECODER_STATE_KEY, null); return false; }
protected boolean doDecode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception { if (in.remaining() >= PAYLOAD_SIZE) { byte[] buf = new byte[in.remaining()]; in.get(buf); // first 7 bytes are the sensor ID, last is the status // and the result message will look something like // MachineID=2371748;Status=Good StringBuilder sb = new StringBuilder(); sb.append("MachineID=") .append(new String(buf, 0, PAYLOAD_SIZE - 1)).append(";") .append("Status="); if (buf[PAYLOAD_SIZE - 1] == '1') { sb.append("Good"); } else { sb.append("Failure"); } out.write(sb.toString()); return true; } else { return false; } }
@Override public boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { // log.debug("doDecode(...)..."); XMLLightweightParser parser = (XMLLightweightParser) session .getAttribute(XmppIoHandler.XML_PARSER); parser.read(in); if (parser.areThereMsgs()) { for (String stanza : parser.getMsgs()) { out.write(stanza); } } return !in.hasRemaining(); }
@Override public boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { log.debug("doDecode(...)..."); // Get the XML light parser from the IoSession XMLLightweightParser parser = (XMLLightweightParser) session .getAttribute("XML-PARSER"); // Parse as many stanzas as possible from the received data parser.read(in); if (parser.areThereMsgs()) { for (String stanza : parser.getMsgs()) { out.write(stanza); } } return !in.hasRemaining(); }
@Override public boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { log.debug("doDecode(...)..."); XMLLightweightParser parser = (XMLLightweightParser) session .getAttribute("XML_PARSER"); parser.read(in); if (parser.areThereMsgs()) { for (String stanza : parser.getMsgs()) { out.write(stanza); } } return !in.hasRemaining(); }