コード例 #1
0
  @Override
  protected boolean doDecode(IoSession arg0, IoBuffer arg1, ProtocolDecoderOutput arg2)
      throws Exception {
    if (arg1.remaining() >= 8) {

      arg1.mark();
      HubMessage message = new HubMessage();
      int type = arg1.getInt();
      int length = arg1.getInt();
      if (length != 0) {
        if (arg1.remaining() >= length) {
          message.setMessageType(type);
          message.setMessageLength(length);
          byte extendedData[] = new byte[length];
          arg1.get(extendedData);
          message.setExtendedData(extendedData);
          arg2.write(message);
          return true;
        } else {
          arg1.reset();
          return false;
        }
      } else {
        message.setMessageType(type);
        message.setMessageLength(length);
        arg2.write(message);
        return true;
      }
    }
    return false;
  }
 protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
     throws Exception {
   DecoderState decoderState = (DecoderState) session.getAttribute(DECODER_STATE_KEY);
   if (decoderState == null) {
     decoderState = new DecoderState();
     session.setAttribute(DECODER_STATE_KEY, decoderState);
   }
   if (decoderState.image1 == null) {
     // try to read first image
     if (in.prefixedDataAvailable(4, MAX_IMAGE_SIZE)) {
       decoderState.image1 = readImage(in);
     } else {
       // not enough data available to read first image
       return false;
     }
   }
   if (decoderState.image1 != null) {
     // try to read second image
     if (in.prefixedDataAvailable(4, MAX_IMAGE_SIZE)) {
       BufferedImage image2 = readImage(in);
       ImageResponse imageResponse = new ImageResponse(decoderState.image1, image2);
       out.write(imageResponse);
       decoderState.image1 = null;
       return true;
     } else {
       // not enough data available to read second image
       return false;
     }
   }
   return false;
 }
コード例 #3
0
 @Override
 protected DecodingState finishDecode(List<Object> childProducts, ProtocolDecoderOutput out)
     throws Exception {
   for (Object child : childProducts) {
     MutableHttpResponse response = (MutableHttpResponse) child;
     String beanName = response.getHeader(Constants.HTTP_HEADER_BEANNAME);
     String methodName = response.getHeader(Constants.HTTP_HEADER_METHOD);
     String sequence = response.getHeader(Constants.HTTP_HEADER_SEQ);
     IoBuffer content = response.getContent();
     out.write(beanName);
     out.write(methodName);
     out.write(Integer.parseInt(sequence));
     out.write(new IoBufferInputStream(content));
   }
   return null;
 }
コード例 #4
0
 @Override
 protected DecodingState finishDecode(boolean foundCRLF, ProtocolDecoderOutput out)
     throws Exception {
   if (foundCRLF) {
     out.write(headers);
     return null;
   } else {
     return READ_HEADER_NAME;
   }
 }
コード例 #5
0
  /** 解码 */
  public void decode(IoSession session, IoBuffer buf, ProtocolDecoderOutput out) throws Exception {
    IoBuffer allBuf = IoBuffer.allocate(100).setAutoExpand(true);
    while (buf.hasRemaining()) {
      byte b = buf.get();
      System.out.println("b:" + b);
      allBuf.put(b);
    }

    MinaProtocol protocol = null;
    // 获取协议tag
    //    byte tag=buf.get();
    // 获取协议体长度
    int length = buf.getInt();
    // 取出协议体
    byte[] bodyData = new byte[length];
    buf.get(bodyData);
    // 为解析数据做准备
    // 检测协议
    IoBuffer tempBuf = IoBuffer.allocate(100).setAutoExpand(true);
    //    tempBuf.put(tag);
    tempBuf.putInt(length);
    tempBuf.put(bodyData);
    tempBuf.flip();
    if (!canDecode(tempBuf)) {
      return;
    }
    // 协议体buf
    IoBuffer bodyBuf = IoBuffer.allocate(100).setAutoExpand(true);
    bodyBuf.put(bodyData);
    bodyBuf.flip();
    // 整个协议buf
    //    allBuf.put(tag);
    allBuf.putInt(length);
    allBuf.put(bodyData);
    allBuf.flip();
    //
    //    if(tag == Constant.REQ) {
    //      JMessageProtocolReq req=new JMessageProtocolReq();
    //      short functionCode=bodyBuf.getShort();
    //      String content=bodyBuf.getString(charset.newDecoder());
    //      req.setFunctionCode(functionCode);
    //      req.setContent(content);
    //      protocol=req;
    //    } else if(tag == Constant.RES) {
    //      JMessageProtocolRes res=new JMessageProtocolRes();
    //      byte resultCode=bodyBuf.get();
    //      String content=bodyBuf.getString(charset.newDecoder());
    //      res.setResultCode(resultCode);
    //      res.setContent(content);
    //      protocol=res;
    //    } else {
    //      LOG.error("未定义的Tag");
    //    }
    out.write(protocol);
  }
コード例 #6
0
  @Override
  protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) {

    // Get the state of the current message and
    // Skip what we have already scanned
    DecoderState state = decoderState(session);
    in.position(state.current());

    while (in.hasRemaining()) {
      byte current = in.get();

      // If it is the start byte and mark the position
      if (current == config.getStartByte()) {
        state.markStart(in.position() - 1);
      }
      // If it is the end bytes, extract the payload and return
      if (state.previous() == config.getEndByte1() && current == config.getEndByte2()) {

        // Remember the current position and limit.
        int position = in.position();
        int limit = in.limit();
        LOG.debug("Message ends at position {} with length {}", position, position - state.start());
        try {
          in.position(state.start());
          in.limit(position);
          // The bytes between in.position() and in.limit()
          // now contain a full MLLP message including the
          // start and end bytes.
          out.write(
              config.isProduceString()
                  ? parseMessageToString(in.slice(), charsetDecoder(session))
                  : parseMessageToByteArray(in.slice()));
        } catch (CharacterCodingException cce) {
          throw new IllegalArgumentException("Exception while finalizing the message", cce);
        } finally {
          // Reset position, limit, and state
          in.limit(limit);
          in.position(position);
          state.reset();
        }
        return true;
      }
      // Remember previous byte in state object because the buffer could
      // be theoretically exhausted right between the two end bytes
      state.markPrevious(current);
    }

    // Could not find a complete message in the buffer.
    // Reset to the initial position and return false so that this method
    // is called again with more data.
    LOG.debug("No complete message yet at position {} ", in.position());
    state.markCurrent(in.position());
    in.position(0);
    return false;
  }
コード例 #7
0
 @Override
 public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
   LOG.info("decode invoked with buffer {}", in);
   in.reset();
   int startPos = in.markValue();
   // Common decoding part
   PublishMessage message = new PublishMessage();
   if (!decodeCommonHeader(message, in)) {
     LOG.info("decode ask for more data after {}", in);
     in.reset();
     return;
   }
   if (((int) session.getAttribute(MQTTDecoder.PROTOCOL_VERSION)) == MQTTProtocol.VERSION_3_1_1) {
     if (message.getQos() == AbstractMessage.QOSType.MOST_ONE && message.isDupFlag()) {
       // bad protocol, if QoS=0 => DUP = 0
       throw new CorruptedFrameException(
           "Received a PUBLISH with QoS=0 & DUP = 1, MQTT 3.1.1 violation");
     }
     if (message.getQos() == AbstractMessage.QOSType.RESERVED) {
       throw new CorruptedFrameException(
           "Received a PUBLISH with QoS flags setted 10 b11, MQTT 3.1.1 violation");
     }
   }
   int remainingLength = message.getRemainingLength();
   // Topic name
   String topic = MQTTProtocol.decodeString(in);
   if (topic == null) {
     in.reset();
     return;
   }
   if (topic.contains("+") || topic.contains("#")) {
     throw new CorruptedFrameException(
         "Received a PUBLISH with topic containting wild card chars, topic: " + topic);
   }
   message.setTopicName(topic);
   if (message.getQos() == AbstractMessage.QOSType.LEAST_ONE
       || message.getQos() == AbstractMessage.QOSType.EXACTLY_ONCE) {
     message.setMessageID(in.getUnsignedShort());
   }
   int stopPos = in.position();
   // read the payload
   int payloadSize =
       remainingLength
           - (stopPos - startPos - 2)
           + (MQTTProtocol.numBytesToEncode(remainingLength) - 1);
   LOG.info("payload size: {}", payloadSize);
   if (in.remaining() < payloadSize) {
     in.reset();
     return;
   }
   byte[] payload = new byte[payloadSize];
   in.get(payload);
   message.setPayload(payload);
   out.write(message);
 }
コード例 #8
0
  @Override
  public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    // TODO Auto-generated method stub

    int limit = in.limit();
    byte[] bytes = new byte[limit];

    in.get(bytes);

    out.write(bytes);
  }
コード例 #9
0
  public MessageDecoderResult decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
      throws Exception {
    // Common decoding part
    MessageIDMessage message = createMessage();
    if (decodeCommonHeader(message, in) == NEED_DATA) {
      return NEED_DATA;
    }

    // read  messageIDs
    message.setMessageID(Utils.readWord(in));
    out.write(message);
    return OK;
  }
コード例 #10
0
  @Override
  protected boolean doDecode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out)
      throws Exception {
    // Get the XML light parser from the IoSession
    XMLLightweightParser parser =
        (XMLLightweightParser) session.getAttribute(ConnectionHandler.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();
  }
コード例 #11
0
  @Override
  public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    in.reset();
    // Common decoding part
    ConnAckMessage message = new ConnAckMessage();
    if (!decodeCommonHeader(message, 0x00, in)) {
      in.reset();
      return;
    }
    // skip reserved byte
    in.skip(1);

    // read  return code
    message.setReturnCode(in.get());
    out.write(message);
  }
コード例 #12
0
 /**
  * Decodes protobuf messages of given type from buffer. If not enough data has been presented
  * delegates to the {@link CumulativeProtocolDecoder} base class to read more data from the wire.
  *
  * <p>It uses instance of internal {@link SizeContext} class to calculate size of buffer expected
  * by the given type of message. The size of every message that arrives on the wire is specified
  * by the prepending varint value.
  *
  * @param session The session used to store internal {@link SizeContext}.
  * @param in The buffer used to read messages if contains enough data.
  * @param out The output for messages decoded from data provided.
  * @see ProtobufEncoder
  * @see SizeContext
  */
 @Override
 protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
     throws Exception {
   SizeContext ctx = SizeContext.get(session, in);
   if (ctx.hasEnoughData(in)) {
     try {
       Message.Builder builder = prototype.newBuilderForType();
       ctx.getInputStream(in).readMessage(builder, extentions);
       out.write(builder.build());
       return true;
     } finally {
       ctx.shiftPositionAndReset(session, in);
     }
   }
   return false;
 }
コード例 #13
0
  @Override
  public MessageDecoderResult decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
      throws Exception {
    // =================结合CumulativeProtocolDecoder================//
    Context ctx = getContext(session); // 获取session  的context

    long matchCount = ctx.getMatchLength(); // 目前已获取的数据
    long length = ctx.getLength(); // 数据总长度
    IoBuffer buffer = ctx.getBuffer(); // 数据存入buffer

    // 第一次取数据
    if (length == 0) {
      length = in.getLong();
      // 保存第一次获取的长度
      ctx.setLength(length);
      matchCount = in.remaining();
      ctx.setMatchLength(matchCount);
    } else {
      matchCount += in.remaining();
      ctx.setMatchLength(matchCount);
    }
    if (in.hasRemaining()) { // 如果buff中还有数据
      if (matchCount < length) {
        buffer.put(in); // 添加到保存数据的buffer中
      }
      if (matchCount >= length) { // 如果已经发送的数据的长度>=目标数据的长度,则进行解码
        byte[] b = new byte[(int) length];
        byte[] temp = new byte[(int) length];
        in.get(temp, 0, (int) (length - buffer.position())); // 最后一次in的数据可能有多的
        buffer.put(temp);
        // 一定要添加以下这一段,否则不会有任何数据,因为,在执行in.put(buffer)时buffer的起始位置已经移动到最后,所有需要将buffer的起始位置移动到最开始
        buffer.flip();
        buffer.get(b);
        File_ServiceRadio file = new File_ServiceRadio();
        file.setFileContent(b);
        out.write(file);

        ctx.reset();
        return MessageDecoderResult.OK;

      } else {
        ctx.setBuffer(buffer);
        return MessageDecoderResult.NEED_DATA;
      }
    }
    return MessageDecoderResult.NEED_DATA;
  }
コード例 #14
0
  /** 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;
    }
  }
コード例 #15
0
  @Override
  public MessageDecoderResult decode(IoSession ioSession, IoBuffer in, ProtocolDecoderOutput out)
      throws Exception {

    int hasCount = 0;
    while (in.hasRemaining()) {
      hasCount++;
      if (hasCount == 17) {
        byte bytes[] = new byte[17];
        in.get(bytes);
        Reply_SweepRange sweep = new Reply_SweepRange();
        sweep.setContent(bytes);
        out.write(sweep);
        return MessageDecoderResult.OK;
      }
    }
    return MessageDecoderResult.NEED_DATA;
  }
コード例 #16
0
 @Override
 protected DecodingState finishDecode(List<Object> childProducts, ProtocolDecoderOutput out)
     throws Exception {
   if (childProducts.size() < 4) {
     return null;
   }
   int childs = childProducts.size();
   for (int i = 0; i < childs; i = i + 4) {
     AsyncClientResponse response = new AsyncClientResponse();
     response.setBeanName((String) childProducts.get(i));
     response.setMethodName((String) childProducts.get(i + 1));
     response.setSequence((Integer) childProducts.get(i + 2));
     response.setInputStream((InputStream) childProducts.get(i + 3));
     out.write(response);
     charsetDecoder.reset();
   }
   return null;
 }
コード例 #17
0
  @Override
  protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
      throws Exception {

    boolean has = in.prefixedDataAvailable(4, Integer.MAX_VALUE);
    if (has) {
      int length = in.getInt();
      byte[] bytes = new byte[length];
      in.get(bytes);
      byte[] messageType = new byte[Constant.MESSAGE_TYPE_COUNT];
      System.arraycopy(bytes, 0, messageType, 0, Constant.MESSAGE_TYPE_COUNT);
      int type = ByteUtils.ByteArray2Int(messageType);
      byte[] bodyByte = new byte[length - Constant.MESSAGE_TYPE_COUNT];
      System.arraycopy(
          bytes, Constant.MESSAGE_TYPE_COUNT, bodyByte, 0, length - Constant.MESSAGE_TYPE_COUNT);
      AbstractChatMessage chatMessage = this.getMessageType(type);
      chatMessage.bytes2Body(bodyByte);
      chatMessage.setMessageType(type);
      out.write(chatMessage);
      return true;
    }
    return false;
  }
コード例 #18
0
  @Override
  public MessageDecoderResult decode(IoSession session, IoBuffer buffer, ProtocolDecoderOutput out)
      throws Exception {
    StartOnDemandMessage message = new StartOnDemandMessage();

    buffer.getInt();
    buffer.get();
    int numTransients = buffer.getInt();
    if (numTransients > 0) {
      OnDemandRequest[] transients = new OnDemandRequest[numTransients];

      for (int i = 0; i < numTransients; ++i) {
        OnDemandRequest request = new OnDemandRequest();
        request.setAttributeAlias(buffer.getInt());
        int numIdPatterns = buffer.getInt();
        if (numIdPatterns > 0) {
          String[] idPatterns = new String[numIdPatterns];

          for (int j = 0; j < numIdPatterns; ++j) {
            int idLength = buffer.getInt();
            byte[] idBytes = new byte[idLength];
            buffer.get(idBytes);
            idPatterns[j] = new String(idBytes, "UTF-16BE");
          }

          request.setIdPatterns(idPatterns);
        }
      }

      message.setRequests(transients);
    }

    out.write(message);

    return MessageDecoderResult.OK;
  }
コード例 #19
0
ファイル: MinaDecoder.java プロジェクト: kekkaishis/oceanbase
 @Override
 protected boolean doDecode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out)
     throws Exception {
   final int origonPos = in.position();
   if (in.remaining() < 16) {
     in.position(origonPos);
     return false;
   }
   int magic = in.getInt();
   if (magic != Const.MAGIC)
     throw new IOException("flag error, except: " + Const.MAGIC + ", but get " + magic);
   int request = in.getInt();
   int pcode = in.getInt();
   int len = in.getInt();
   if (in.remaining() < len) {
     in.position(origonPos);
     return false;
   }
   byte[] data = new byte[len];
   in.get(data);
   BaseResponsePacket packet = PacketCode.createPacket(pcode, request, data);
   out.write(packet);
   return true;
 }
コード例 #20
0
ファイル: MultiLineDecoder.java プロジェクト: Eising/opennms
  /** {@inheritDoc} */
  @Override
  protected boolean doDecode(
      final IoSession session, final IoBuffer in, final ProtocolDecoderOutput out)
      throws Exception {
    MultilineOrientedResponse response =
        (MultilineOrientedResponse) session.getAttribute(CURRENT_RESPONSE);
    if (response == null) {
      response = new MultilineOrientedResponse();
      session.setAttribute(CURRENT_RESPONSE, response);
    }
    // Remember the initial position.
    final int start = in.position();

    // Now find the first CRLF in the buffer.
    byte previous = 0;
    while (in.hasRemaining()) {
      final byte current = in.get();

      if (previous == '\r' && current == '\n') {
        // Remember the current position and limit.
        final int position = in.position();
        final int limit = in.limit();
        try {
          in.position(start);
          in.limit(position);
          // The bytes between in.position() and in.limit()
          // now contain a full CRLF terminated line.

          // If the multiline indicator is on this line then add the line to
          // the response object and continue to process the next line
          if (checkIndicator(in.slice())) {
            response.addLine(in.getString(getCharset().newDecoder()));
          } else {
            // Otherwise, add the current line and then submit the response
            // to the ProtocolDecoderOutput instance
            response.addLine(in.getString(getCharset().newDecoder()));
            out.write(response);
            session.removeAttribute(CURRENT_RESPONSE);
            return true;
          }

        } finally {
          // Set the position to point right after the
          // detected line and set the limit to the old
          // one.
          in.position(position);
          in.limit(limit);
        }
        // Decoded one line; CumulativeProtocolDecoder will
        // call me again until I return false. So just
        // return true until there are no more lines in the
        // buffer.
        return true;
      }

      previous = current;
    }
    // Could not find CRLF in the buffer. Reset the initial
    // position to the one we recorded above.
    in.position(start);

    return false;
  }
コード例 #21
0
 @Override
 public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
   out.write(in.duplicate());
   in.skip(in.remaining());
 }
コード例 #22
0
 @Override
 protected DecodingState finishDecode(int value, ProtocolDecoderOutput out)
     throws Exception {
   out.write(value);
   return bodyState;
 }
コード例 #23
0
  /** 把二进制流解码为服务器使用的数据包格式 */
  @Override
  protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
      throws Exception {
    //      private short size;//包大小
    //      private short type;//版本号
    //      private short code;//包类型
    //      private int roleid; // 玩家ID
    IoBuffer newBuf = in.slice();
    // size
    System.out.println(newBuf);
    int size = newBuf.getInt();
    System.out.printf("c size = %d\n", size);
    int length = newBuf.getInt();
    System.out.printf("c size = %d\n", length);
    byte[] bytesaa = new byte[length];
    newBuf.get(bytesaa);
    String as = null;
    try {
      as = new String(bytesaa, "UTF-8");
    } catch (UnsupportedEncodingException e) {
    }

    System.out.println(as);
    Netmessage res = new Netmessage();
    short type = newBuf.getShort();
    short code = newBuf.getShort();
    int roleid = newBuf.getInt();
    // int roleid=newBuf.getInt();
    System.out.printf("type =  %d code = %d roleid = %d\n", (int) type, (int) code, roleid);
    res.writeDataPack((short) size, type, code, roleid);

    // BODY
    int bodyLen = size - 10;
    if (bodyLen > 0) {
      byte[] bytes = new byte[bodyLen];
      in.get(bytes, 0, bodyLen);
      res.writeData(bytes, size);
    }
    out.write(res);

    if (size <= 0 || size >= Short.MAX_VALUE) {
      // 非法的数据长度
      log.debug("Message Length Invalid size = " + size + ", throw this Message.");
      return true;
    }
    System.out.print(newBuf.getHexDump());

    // 000A 0001 0001 0000 0001
    System.out.printf("buffer size = %d", in.remaining());
    if (size > in.remaining()) {
      // 数据还不够读取,等待下一次读取
      System.out.printf(
          "Data not integrity. there is a lack of " + (size - newBuf.remaining()) + " bytes.");
      return true;
    }
    //        Netmessage res=new Netmessage();
    //        short type=newBuf.getShort();
    //        short code=newBuf.getShort();
    //        int roleid=newBuf.getInt();
    //        //int roleid=newBuf.getInt();
    //        System.out.printf("type =  %d code = %d roleid = %d\n",(int)type,(int)code,roleid);
    //        res.writeDataPack((short)size, type, code, roleid);
    //
    //        // BODY
    //        int bodyLen = size-10;
    //        if (bodyLen > 0) {
    //            byte[] bytes = new byte[bodyLen];
    //            in.get(bytes, 0, bodyLen);
    //            res.writeData(bytes,size);
    //        }
    out.write(res);
    return false;
  }