@Override
  protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf)
      throws Exception {

    char marker = (char) buf.getByte(buf.readerIndex());

    while (marker != '*' && marker != '$' && buf.readableBytes() > 0) {
      buf.skipBytes(1);
      if (buf.readableBytes() > 0) {
        marker = (char) buf.getByte(buf.readerIndex());
      }
    }

    if (marker == '*') {

      // Return text message
      int index = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) '#');
      if (index != -1) {
        return buf.readBytes(index + 1 - buf.readerIndex());
      }

    } else if (marker == '$' && buf.readableBytes() >= MESSAGE_LENGTH) {

      // Return binary message
      return buf.readBytes(MESSAGE_LENGTH);
    }

    return null;
  }
  /*
   * (non-Javadoc)
   *
   * @see
   * org.jboss.netty.handler.codec.oneone.OneToOneDecoder#decode(org.jboss
   * .netty.channel.ChannelHandlerContext, org.jboss.netty.channel.Channel,
   * java.lang.Object)
   */
  @Override
  protected Object decode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
    Message message = (Message) msg;
    long commandId = ((Long) message.getHeader().getCommandId()).longValue();

    if (packetType.getCommandId() != commandId) return msg;

    ReportRequestMessage requestMessage = new ReportRequestMessage();

    requestMessage.setHeader(message.getHeader());
    requestMessage.setBodyBuffer(message.getBodyBuffer());

    ChannelBuffer bodyBuffer = ChannelBuffers.copiedBuffer(message.getBodyBuffer());

    requestMessage.setSequenceNumber(
        DefaultSequenceNumberUtil.bytes2SequenceN(
            bodyBuffer.readBytes(ReportRequest.SUBMITSEQUENCENUMBER.getLength()).array()));
    requestMessage.setReporttype(bodyBuffer.readUnsignedByte());
    requestMessage.setUsernumber(
        bodyBuffer
            .readBytes(ReportRequest.USERNUMBER.getLength())
            .toString(GlobalVars.defaultTransportCharset));
    requestMessage.setState(bodyBuffer.readUnsignedByte());
    requestMessage.setErrorcode(bodyBuffer.readUnsignedByte());
    requestMessage.setReserve(
        bodyBuffer
            .readBytes(ReportRequest.RESERVE.getLength())
            .toString(GlobalVars.defaultTransportCharset));

    return requestMessage;
  }
  @Override
  protected Object decode(
      ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer, DecodingState state)
      throws Exception {
    switch (state) {
      case COMMAND_LENGTH:
        commandLength = buffer.readInt();
        checkpoint(DecodingState.COMMAND);
      case COMMAND:
        byte[] commandBytes = new byte[commandLength];
        buffer.readBytes(commandBytes, 0, commandLength);
        String commandJson = new String(commandBytes, CharsetUtil.UTF_8);
        command = gson.fromJson(commandJson, EuchreCommand.class);
        checkpoint(DecodingState.PAYLOAD_LENGTH);
      case PAYLOAD_LENGTH:
        payloadLength = buffer.readInt();
        checkpoint(DecodingState.PAYLOAD);
      case PAYLOAD:
        byte[] payloadBytes = new byte[payloadLength];
        buffer.readBytes(payloadBytes, 0, payloadLength);
        payload = new String(payloadBytes, CharsetUtil.UTF_8);
    }

    try {
      return new CommandPayloadDecodedModel(command, payload);
    } finally {
      reset();
    }
  }
 /**
  * @param headerLength
  * @param middleLength
  * @param endLength
  * @param buf
  * @return the new AuthentPacket from buffer
  * @throws OpenR66ProtocolPacketException
  */
 public static AuthentPacket createFromBuffer(
     int headerLength, int middleLength, int endLength, ChannelBuffer buf)
     throws OpenR66ProtocolPacketException {
   if (headerLength - 1 <= 0) {
     throw new OpenR66ProtocolPacketException("Not enough data");
   }
   if (middleLength <= 0) {
     throw new OpenR66ProtocolPacketException("Not enough data");
   }
   if (endLength < 5) {
     throw new OpenR66ProtocolPacketException("Not enough data");
   }
   final byte[] bheader = new byte[headerLength - 1];
   final byte[] bmiddle = new byte[middleLength];
   if (headerLength - 1 > 0) {
     buf.readBytes(bheader);
   }
   if (middleLength > 0) {
     buf.readBytes(bmiddle);
   }
   // end part
   Integer newId = buf.readInt();
   byte valid = buf.readByte();
   String version =
       R66Versions.V2_4_12.getVersion(); // first base reference where it is unacceptable
   if (endLength > 5) {
     // version
     byte[] bversion = new byte[endLength - 5];
     buf.readBytes(bversion);
     version = new String(bversion);
   }
   final String sheader = new String(bheader);
   return new AuthentPacket(sheader, bmiddle, newId, valid, version);
 }
  /**
   * Handles a received {@link MBeanServerConnection} invocation
   *
   * @param channel The channel the request was received on
   * @param remoteAddress The remote address of the caller
   * @param buffer THe buffer received
   */
  public static void handleJMXRequest(
      Channel channel, SocketAddress remoteAddress, ChannelBuffer buffer) {
    buffer.resetReaderIndex();
    /* The request write */
    //		cb.writeByte(OpCode.JMX_REQUEST.op());  // 1
    //		cb.writeBytes(domainInfoData);   // domain data
    //		cb.writeInt(reqId);					// 4
    //		cb.writeByte(methodToKey.get(method)); // 1
    //		cb.writeInt(sargs.length);  			// 4
    //		cb.writeBytes(sargs);		           // sargs.length
    Object result = null;
    MBeanServerConnection server = null;
    buffer.skipBytes(1);
    byte domainIndicator = buffer.readByte();
    if (domainIndicator == 0) {
      server = JMXHelper.getHeliosMBeanServer();
    } else {
      byte[] domainBytes = new byte[domainIndicator];
      buffer.readBytes(domainBytes);
      String domain = new String(domainBytes);
      server = JMXHelper.getLocalMBeanServer(true, domain);
      if (server == null) {
        result = new SmallException("Failed to locate MBeanServer for domain [" + domain + "]");
      }
    }
    int reqId = buffer.readInt();
    byte methodId = buffer.readByte();
    if (result == null) {
      int payloadSize = buffer.readInt();
      byte[] payload = new byte[payloadSize];
      buffer.readBytes(payload);
      Object[] params = getInput(payload);
      Method targetMethod = null;
      try {
        targetMethod = keyToMethod.get(methodId);
        if (targetMethod == null) {
          result =
              new SmallException(
                  "Failed to handle MBeanServerConnection invocation because method Op Code ["
                      + methodId
                      + "] was not recognized");
        } else {
          if ("addNotificationListener".equals(targetMethod.getName())
              && !targetMethod.getParameterTypes()[1].equals(ObjectName.class)) {

          } else if ("removeNotificationListener".equals(targetMethod.getName())
              && !targetMethod.getParameterTypes()[1].equals(ObjectName.class)) {

          } else {
            result = targetMethod.invoke(server, params);
          }
        }
      } catch (Throwable t) {
        SimpleLogger.warn("Failed to invoke [", targetMethod, "]", t);
        result = new SmallException(t.toString());
      }
    }
    writeJMXResponse(reqId, methodId, channel, remoteAddress, result);
  }
  /**
   * Reads the channel buffer and returns object of NodeAttributesTlv.
   *
   * @param c input channel buffer
   * @param hLength length
   * @return object of NodeAttributesTlv
   * @throws PcepParseException if mandatory fields are missing
   */
  public static PcepValueType read(ChannelBuffer c, short hLength) throws PcepParseException {

    // Node Descriptor Sub-TLVs (variable)
    List<PcepValueType> llNodeAttributesSubTLVs = new LinkedList<>();

    ChannelBuffer tempCb = c.readBytes(hLength);

    while (TLV_HEADER_LENGTH <= tempCb.readableBytes()) {
      PcepValueType tlv;
      short hType = tempCb.readShort();
      int iValue = 0;
      short length = tempCb.readShort();
      switch (hType) {
        case NodeFlagBitsSubTlv.TYPE:
          byte cValue = tempCb.readByte();
          tlv = new NodeFlagBitsSubTlv(cValue);
          break;
        case OpaqueNodePropertiesSubTlv.TYPE:
          tlv = OpaqueNodePropertiesSubTlv.read(tempCb, length);
          break;
        case NodeNameSubTlv.TYPE:
          tlv = NodeNameSubTlv.read(tempCb, length);
          break;
        case IsisAreaIdentifierSubTlv.TYPE:
          tlv = IsisAreaIdentifierSubTlv.read(tempCb, length);
          break;
        case IPv4RouterIdOfLocalNodeSubTlv.TYPE:
          iValue = tempCb.readInt();
          tlv = new IPv4RouterIdOfLocalNodeSubTlv(iValue);
          break;
        case IPv6RouterIdofLocalNodeSubTlv.TYPE:
          byte[] ipv6Value = new byte[IPv6RouterIdofLocalNodeSubTlv.VALUE_LENGTH];
          tempCb.readBytes(ipv6Value, 0, IPv6RouterIdofLocalNodeSubTlv.VALUE_LENGTH);
          tlv = new IPv6RouterIdofLocalNodeSubTlv(ipv6Value);
          break;
        default:
          throw new PcepParseException("Unsupported Sub TLV type :" + hType);
      }

      // Check for the padding
      int pad = length % 4;
      if (0 < pad) {
        pad = 4 - pad;
        if (pad <= tempCb.readableBytes()) {
          tempCb.skipBytes(pad);
        }
      }

      llNodeAttributesSubTLVs.add(tlv);
    }

    if (0 < tempCb.readableBytes()) {

      throw new PcepParseException("Sub Tlv parsing error. Extra bytes received.");
    }
    return new NodeAttributesTlv(llNodeAttributesSubTLVs);
  }
  private void readFixedLengthContent(ChannelBuffer buffer) {
    long length = getContentLength(message);
    assert length <= Integer.MAX_VALUE;

    if (content == null) {
      content = buffer.readBytes((int) length);
    } else {
      content.writeBytes(buffer.readBytes((int) length));
    }
  }
 @Override
 public EncryptionKeyRequestMessage decode(ChannelBuffer buffer) {
   String sessionId = ChannelBufferUtils.readString(buffer);
   int length = buffer.readShort() & 0xFFFF;
   byte[] publicKey = new byte[length];
   buffer.readBytes(publicKey);
   int tokenLength = buffer.readShort() & 0xFFFF;
   byte[] token = new byte[tokenLength];
   buffer.readBytes(token);
   return new EncryptionKeyRequestMessage(sessionId, false, publicKey, token);
 }
  public void readFrom(ChannelBuffer data) {
    this.fieldId = data.readShort();
    this.offset = data.readShort();
    this.length = data.readShort();
    data.readShort();

    value = new byte[OFGlobal.OFP_MAX_FIELD_LENGTH_IN_BYTE];
    data.readBytes(value);

    mask = new byte[OFGlobal.OFP_MAX_FIELD_LENGTH_IN_BYTE];
    data.readBytes(mask);
  }
Exemple #10
0
  /**
   * Reads from the channel buffer and parses AsPath.
   *
   * @param cb ChannelBuffer
   * @return object of AsPath
   * @throws BgpParseException while parsing AsPath
   */
  public static AsPath read(ChannelBuffer cb) throws BgpParseException {
    List<Short> aspathSet = new ArrayList<>();
    List<Short> aspathSeq = new ArrayList<>();
    ChannelBuffer tempCb = cb.copy();
    Validation validation = Validation.parseAttributeHeader(cb);

    if (cb.readableBytes() < validation.getLength()) {
      Validation.validateLen(
          BgpErrorType.UPDATE_MESSAGE_ERROR,
          BgpErrorType.ATTRIBUTE_LENGTH_ERROR,
          validation.getLength());
    }
    // if fourth bit is set, length is read as short otherwise as byte , len includes type, length
    // and value
    int len =
        validation.isShort()
            ? validation.getLength() + Constants.TYPE_AND_LEN_AS_SHORT
            : validation.getLength() + Constants.TYPE_AND_LEN_AS_BYTE;
    ChannelBuffer data = tempCb.readBytes(len);
    if (validation.getFirstBit() && !validation.getSecondBit() && validation.getThirdBit()) {
      throw new BgpParseException(
          BgpErrorType.UPDATE_MESSAGE_ERROR, BgpErrorType.ATTRIBUTE_FLAGS_ERROR, data);
    }

    ChannelBuffer tempBuf = cb.readBytes(validation.getLength());
    while (tempBuf.readableBytes() > 0) {
      byte pathSegType = tempBuf.readByte();
      // no of ASes
      byte pathSegLen = tempBuf.readByte();
      int length = pathSegLen * ASNUM_SIZE;
      if (tempBuf.readableBytes() < length) {
        Validation.validateLen(
            BgpErrorType.UPDATE_MESSAGE_ERROR, BgpErrorType.ATTRIBUTE_LENGTH_ERROR, length);
      }
      ChannelBuffer aspathBuf = tempBuf.readBytes(length);
      while (aspathBuf.readableBytes() > 0) {
        short asNum;
        asNum = aspathBuf.readShort();
        switch (pathSegType) {
          case ASPATH_SET_TYPE:
            aspathSet.add(asNum);
            break;
          case ASPATH_SEQ_TYPE:
            aspathSeq.add(asNum);
            break;
          default:
            log.debug("Other type Not Supported:" + pathSegType);
        }
      }
    }
    return new AsPath(aspathSet, aspathSeq);
  }
Exemple #11
0
  @Override
  protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer)
      throws Exception {
    // wait for prefix
    if (buffer.readableBytes() < 4) {
      return null;
    }

    int length = buffer.getInt(buffer.readerIndex());
    // wait for the complete event
    if (buffer.readableBytes() < length + 4) {
      return null;
    }

    // skip package length header
    buffer.skipBytes(4);
    // decode
    int typeLength = buffer.readInt();
    String type = buffer.toString(buffer.readerIndex(), typeLength, "UTF-8");
    int eventLength = length - typeLength;
    byte[] eventBytes = new byte[eventLength];
    buffer.skipBytes(typeLength);
    buffer.readBytes(eventBytes);
    return new Event(type, eventBytes);
  }
  private boolean handleRevision1Response(ChannelHandlerContext ctx, int payloadLength)
      throws Exception {
    int code = buffered.readInt();

    int descriptionLength = buffered.readInt();
    byte[] descBytes = new byte[descriptionLength];
    buffered.readBytes(descBytes, 0, descBytes.length);

    String description = new String(descBytes, StandardCharsets.UTF_8);

    logger.debug(
        "Decoded payload with length:[{}], code:[{}], descriptionLength:[{}], description:[{}] on connection [{}]",
        payloadLength,
        code,
        descriptionLength,
        description,
        ctx.getChannel().getLocalAddress());

    if (200 <= code && code <= 299) {
      logger.info(
          "Connected to Found Elasticsearch: [{}]: [{}] on connection [{}]",
          code,
          description,
          ctx.getChannel().getLocalAddress());
      return true;
    } else {
      logger.error(
          "Unable to connect to Found Elasticsearch: [{}]: [{}] on connection [{}]",
          code,
          description,
          ctx.getChannel().getLocalAddress());
      return false;
    }
  }
Exemple #13
0
  @Override
  public void readFrom(ChannelBuffer channelBuffer) throws OspfParseException {

    while (channelBuffer.readableBytes() >= OspfUtil.LSREQUEST_LENGTH) {
      LsRequestPacket lsRequestPacket = new LsRequestPacket();
      lsRequestPacket.setLsType(channelBuffer.readInt());
      byte[] tempByteArray = new byte[OspfUtil.FOUR_BYTES];
      channelBuffer.readBytes(tempByteArray, 0, OspfUtil.FOUR_BYTES);
      lsRequestPacket.setLinkStateId(Ip4Address.valueOf(tempByteArray).toString());
      tempByteArray = new byte[OspfUtil.FOUR_BYTES];
      channelBuffer.readBytes(tempByteArray, 0, OspfUtil.FOUR_BYTES);
      lsRequestPacket.setOwnRouterId(Ip4Address.valueOf(tempByteArray).toString());

      this.addLinkStateRequests(lsRequestPacket);
    }
  }
 @Override
 public WorldEditCUIMessage decode(ChannelBuffer buffer) {
   byte[] data = new byte[buffer.readableBytes()];
   buffer.readBytes(data);
   String message = new String(data, UTF_8_CHARSET);
   return new WorldEditCUIMessage(message);
 }
  @Override
  protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer)
      throws Exception {
    buffer.markReaderIndex();
    final byte[] buf = new byte[5];
    for (int i = 0; i < buf.length; i++) {
      if (!buffer.readable()) {
        buffer.resetReaderIndex();
        return null;
      }

      buf[i] = buffer.readByte();
      if (buf[i] >= 0) {
        int length = CodedInputStream.newInstance(buf, 0, i + 1).readRawVarint32();
        if (length < 0) {
          throw new CorruptedFrameException("negative length: " + length);
        }

        if (buffer.readableBytes() < length) {
          buffer.resetReaderIndex();
          return null;
        } else {
          return buffer.readBytes(length);
        }
      }
    }

    // Couldn't find the byte whose MSB is off.
    throw new CorruptedFrameException("length wider than 32-bit");
  }
  @Override
  protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf)
      throws Exception {

    if (buf.readableBytes() < 10) {
      return null;
    }

    int beginIndex = buf.indexOf(buf.readerIndex(), buf.writerIndex(), new StringFinder("$$"));
    if (beginIndex == -1) {
      return null;
    } else if (beginIndex > buf.readerIndex()) {
      buf.readerIndex(beginIndex);
    }

    int length;

    int flagIndex = buf.indexOf(buf.readerIndex(), buf.writerIndex(), new StringFinder("AA"));
    if (flagIndex != -1 && flagIndex - beginIndex == 6) {
      length = Integer.parseInt(buf.toString(buf.readerIndex() + 2, 4, Charset.defaultCharset()));
    } else {
      length =
          Integer.parseInt(buf.toString(buf.readerIndex() + 2, 2, Charset.defaultCharset()), 16);
    }

    if (length <= buf.readableBytes()) {
      return buf.readBytes(length);
    }

    return null;
  }
 private void setInput(ChannelBuffer decompressed) {
   byte[] in = new byte[decompressed.readableBytes()];
   decompressed.readBytes(in);
   z.next_in = in;
   z.next_in_index = 0;
   z.avail_in = in.length;
 }
Exemple #18
0
  /**
   * Reads from the channel buffer and returns Object of PcepTEObject.
   *
   * @param cb of type channel buffer
   * @return Object of PcepTEObject
   * @throws PcepParseException if mandatory fields are missing
   */
  public static PcepTEObject read(ChannelBuffer cb) throws PcepParseException {
    log.debug("read");

    PcepObjectHeader teObjHeader;
    byte yProtocolId;
    // 2-flags
    boolean bRFlag;
    boolean bSFlag;
    int iTEId;
    LinkedList<PcepValueType> llOptionalTlv;

    teObjHeader = PcepObjectHeader.read(cb);

    // take only TEObject buffer.
    ChannelBuffer tempCb = cb.readBytes(teObjHeader.getObjLen() - OBJECT_HEADER_LENGTH);

    yProtocolId = tempCb.readByte();
    // ignore first two bytes of Flags
    tempCb.readShort();

    Integer iTemp = (int) tempCb.readByte(); // read 3rd byte Flag
    bSFlag = ((iTemp & FLAG_SET_S_FLAG) == FLAG_SET_S_FLAG) ? true : false;
    bRFlag = ((iTemp & FLAG_SET_R_FLAG) == FLAG_SET_R_FLAG) ? true : false;

    iTEId = tempCb.readInt();

    // parse optional TLV
    llOptionalTlv = parseOptionalTlv(tempCb);

    return new PcepTEObjectVer1(teObjHeader, yProtocolId, bRFlag, bSFlag, iTEId, llOptionalTlv);
  }
Exemple #19
0
 @Override
 protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer)
     throws Exception {
   if (opcode == -1) {
     if (buffer.readableBytes() >= 1) {
       opcode = buffer.readByte() & 0xFF;
       opcode = (opcode - cipher.getNextValue()) & 0xFF;
       size = Client.PACKET_SIZES[opcode];
     } else {
       return null;
     }
   }
   if (size == -1) {
     if (buffer.readableBytes() >= 1) {
       size = buffer.readByte() & 0xFF;
     } else {
       return null;
     }
   }
   if (buffer.readableBytes() >= size) {
     final byte[] data = new byte[size];
     buffer.readBytes(data);
     final ChannelBuffer payload = ChannelBuffers.buffer(size);
     payload.writeBytes(data);
     try {
       return new Packet(opcode, Type.FIXED, payload);
     } finally {
       opcode = -1;
       size = -1;
     }
   }
   return null;
 }
  /*
   * (non-Javadoc)
   *
   * @see org.jboss.netty.handler.codec.oneone.OneToOneEncoder#encode(org.jboss
   * .netty.channel.ChannelHandlerContext, org.jboss.netty.channel.Channel, java.lang.Object)
   */
  @Override
  protected Object encode(final ChannelHandlerContext ctx, final Channel channel, final Object msg)
      throws Exception {

    final ChannelBuffer message = (ChannelBuffer) msg;

    final AuthToClientChannelHandler channelHandler =
        (AuthToClientChannelHandler) ctx.getPipeline().getLast();
    final int opcode = message.readUnsignedByte();
    final int size = message.readableBytes();

    final ChannelBuffer frame = ChannelBuffers.buffer(ByteOrder.LITTLE_ENDIAN, (size + 3));
    frame.writeByte(opcode);
    frame.writeShort(size);

    final byte[] tmpa = new byte[message.readableBytes()];
    message.readBytes(tmpa);
    frame.writeBytes(channelHandler.getCrypt().encrypt(tmpa));

    log.debug(String.format("[SEND PACKET] :  0x%02X", opcode));
    final List<String> d =
        breakStringInChunks(new BigInteger(1, tmpa).toString(16).toUpperCase(), 16);
    for (final String string : d) {
      log.debug(string);
    }
    return frame;
  }
  /* (non-Javadoc)
   * @see org.jboss.netty.channel.SimpleChannelHandler#messageReceived(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.MessageEvent)
   */
  @Override
  public void messageReceived(final ChannelHandlerContext context, final MessageEvent e)
      throws Exception {
    String decoded;
    synchronized (stringWriter) {

      // extract the buffer from the message event
      final Object message = e.getMessage();
      if (!(message instanceof ChannelBuffer)) {
        context.sendUpstream(e);
        return;
      }
      final ChannelBuffer buffer = (ChannelBuffer) message;
      if (!buffer.readable()) {
        return;
      }

      // read all bytes from the buffer to the decoder stream
      final byte[] bytes = new byte[buffer.readableBytes()];
      buffer.readBytes(bytes);
      writerOutputStream.write(bytes);
      writerOutputStream.flush();
      decoded = stringWriter.toString();
      stringWriter.getBuffer().setLength(0);
    }

    // push all successfully decoded characters upstream
    Channels.fireMessageReceived(context, decoded, e.getRemoteAddress());
  }
 @Override
 public UnregisterPluginChannelMessage decode(ChannelBuffer buffer) {
   byte[] strData = new byte[buffer.readableBytes()];
   buffer.readBytes(strData);
   String str = new String(strData, ChannelBufferUtils.CHARSET_UTF8);
   return new UnregisterPluginChannelMessage(Arrays.asList(str.split("\0")));
 }
Exemple #23
0
  public static String readString(ChannelBuffer buf, int length, Charset charset) {
    byte[] bytes = new byte[length];
    buf.readBytes(bytes);

    String str = new String(bytes, charset);

    return str;
  }
 /**
  * Read n bytes from this packet buffer, n = length.
  *
  * @param length
  * @return byte[]
  */
 protected final byte[] readB(int length) {
   byte[] result = new byte[length];
   try {
     buf.readBytes(result);
   } catch (Exception e) {
     log.error("Missing byte[] for: " + this);
   }
   return result;
 }
 private static String readString(ChannelBuffer buf) {
   String result = null;
   int index = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) 0);
   if (index > buf.readerIndex()) {
     result = buf.readBytes(index - buf.readerIndex()).toString(StandardCharsets.US_ASCII);
   }
   buf.readByte();
   return result;
 }
 @Override
 public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
   if (e instanceof MessageEvent) {
     MessageEvent event = (MessageEvent) e;
     ChannelBuffer buffer = (ChannelBuffer) event.getMessage();
     while (buffer.readableBytes() > 0) {
       ChannelBuffer newBuffer = ChannelBuffers.dynamicBuffer();
       if (buffer.readableBytes() >= chunkSize) {
         newBuffer.writeBytes(buffer.readBytes(chunkSize));
       } else {
         newBuffer.writeBytes(buffer.readBytes(buffer.readableBytes()));
       }
       Thread.sleep(latency);
       write(ctx, e.getFuture(), newBuffer, event.getRemoteAddress());
     }
   } else {
     ctx.sendDownstream(e);
   }
 }
 @Override
 public void writeBytes(ChannelBuffer src, int length) {
   try {
     byte[] array = new byte[length];
     src.readBytes(array);
     delegate.put(array, array.length);
   } catch (IOException e) {
     throw writeException(e);
   }
 }
Exemple #28
0
 public ChannelBuffer encode(final RtmpMessage message) {
   final ChannelBuffer in = message.encode();
   final RtmpHeader header = message.getHeader();
   if (header.isChunkSize()) {
     final ChunkSize csMessage = (ChunkSize) message;
     logger.debug("encoder new chunk size: {}", csMessage);
     chunkSize = csMessage.getChunkSize();
   } else if (header.isControl()) {
     final Control control = (Control) message;
     if (control.getType() == Control.Type.STREAM_BEGIN) {
       clearPrevHeaders();
     }
   }
   final int channelId = header.getChannelId();
   header.setSize(in.readableBytes());
   final RtmpHeader prevHeader = channelPrevHeaders[channelId];
   if (prevHeader != null // first stream message is always large
       && header.getStreamId() > 0 // all control messages always large
       && header.getTime() > 0) { // if time is zero, always large
     if (header.getSize() == prevHeader.getSize()) {
       header.setHeaderType(RtmpHeader.Type.SMALL);
     } else {
       header.setHeaderType(RtmpHeader.Type.MEDIUM);
     }
     final int deltaTime = header.getTime() - prevHeader.getTime();
     if (deltaTime < 0) {
       logger.warn("negative time: {}", header);
       header.setDeltaTime(0);
     } else {
       header.setDeltaTime(deltaTime);
     }
   } else {
     // otherwise force to LARGE
     header.setHeaderType(RtmpHeader.Type.LARGE);
   }
   channelPrevHeaders[channelId] = header;
   if (logger.isDebugEnabled()) {
     // logger.debug(">> {}", message);
   }
   final ChannelBuffer out =
       ChannelBuffers.buffer(
           RtmpHeader.MAX_ENCODED_SIZE + header.getSize() + header.getSize() / chunkSize);
   boolean first = true;
   while (in.readable()) {
     final int size = Math.min(chunkSize, in.readableBytes());
     if (first) {
       header.encode(out);
       first = false;
     } else {
       out.writeBytes(header.getTinyHeader());
     }
     in.readBytes(out, size);
   }
   return out;
 }
 /**
  * Read this message off the wire from the specified ByteBuffer
  *
  * @param data
  */
 public void readFrom(ChannelBuffer data) {
   this.portNumber = data.readShort();
   if (this.hardwareAddress == null) this.hardwareAddress = new byte[OFP_ETH_ALEN];
   data.readBytes(this.hardwareAddress);
   byte[] name = new byte[16];
   data.readBytes(name);
   // find the first index of 0
   int index = 0;
   for (byte b : name) {
     if (0 == b) break;
     ++index;
   }
   this.name = new String(Arrays.copyOf(name, index), Charset.forName("ascii"));
   this.config = data.readInt();
   this.state = data.readInt();
   this.currentFeatures = data.readInt();
   this.advertisedFeatures = data.readInt();
   this.supportedFeatures = data.readInt();
   this.peerFeatures = data.readInt();
 }
  public byte[] encode(Map<String, Object> value) throws ProtocolException {
    ChannelBuffer cb = ChannelBuffers.dynamicBuffer(100);
    encode(value, cb);

    int writeIndex = cb.writerIndex();
    byte[] result = new byte[writeIndex];

    cb.readBytes(result);

    return result;
  }