Exemplo n.º 1
0
 public void encodeAsByteBuf(ByteBuf var1) {
   var1.writeByte(SUBNEGOTIATION_VERSION.byteValue());
   var1.writeByte(this.username.length());
   var1.writeBytes(this.username.getBytes(CharsetUtil.US_ASCII));
   var1.writeByte(this.password.length());
   var1.writeBytes(this.password.getBytes(CharsetUtil.US_ASCII));
 }
Exemplo n.º 2
0
  private void encodeChunkedContent(
      ChannelHandlerContext ctx, Object msg, int contentLength, List<Object> out) {
    if (contentLength > 0) {
      byte[] length = Integer.toHexString(contentLength).getBytes(CharsetUtil.US_ASCII);
      ByteBuf buf = ctx.alloc().buffer(length.length + 2);
      buf.writeBytes(length);
      buf.writeBytes(CRLF);
      out.add(buf);
      out.add(encodeAndRetain(msg));
      out.add(CRLF_BUF.duplicate());
    }

    if (msg instanceof LastHttpContent) {
      HttpHeaders headers = ((LastHttpContent) msg).trailingHeaders();
      if (headers.isEmpty()) {
        out.add(ZERO_CRLF_CRLF_BUF.duplicate());
      } else {
        ByteBuf buf = ctx.alloc().buffer();
        buf.writeBytes(ZERO_CRLF);
        HttpHeaders.encode(headers, buf);
        buf.writeBytes(CRLF);
        out.add(buf);
      }

      state = ST_INIT;
    } else {
      if (contentLength == 0) {
        // Need to produce some output otherwise an
        // IllegalstateException will be thrown
        out.add(EMPTY_BUFFER);
      }
    }
  }
 @Override
 public void toBytes(ByteBuf buf) {
   buf.writeInt(elementName.length());
   buf.writeBytes(elementName.getBytes());
   buf.writeInt(elementText.length());
   buf.writeBytes(elementText.getBytes());
 }
 @Override
 public void serializeExtendedCommunity(
     final ExtendedCommunities exCommunities, final ByteBuf buffer) {
   final ExtendedCommunity ex = exCommunities.getExtendedCommunity();
   if (ex instanceof TrafficRateExtendedCommunityCase) {
     final TrafficRateExtendedCommunity trafficRate =
         ((TrafficRateExtendedCommunityCase) ex).getTrafficRateExtendedCommunity();
     ByteBufWriteUtil.writeShort(trafficRate.getInformativeAs().getValue().shortValue(), buffer);
     buffer.writeBytes(trafficRate.getLocalAdministrator().getValue());
   } else if (ex instanceof TrafficActionExtendedCommunityCase) {
     final TrafficActionExtendedCommunity trafficAction =
         ((TrafficActionExtendedCommunityCase) ex).getTrafficActionExtendedCommunity();
     buffer.writeZero(RESERVED);
     final BitArray flags = new BitArray(FLAGS_SIZE);
     flags.set(SAMPLE_BIT, trafficAction.isSample());
     flags.set(TERMINAL_BIT, trafficAction.isTerminalAction());
     flags.toByteBuf(buffer);
   } else if (ex instanceof RedirectExtendedCommunityCase) {
     final RedirectExtendedCommunity redirect =
         ((RedirectExtendedCommunityCase) ex).getRedirectExtendedCommunity();
     ByteBufWriteUtil.writeUnsignedShort(
         redirect.getGlobalAdministrator().getValue().intValue(), buffer);
     buffer.writeBytes(redirect.getLocalAdministrator());
   } else if (ex instanceof TrafficMarkingExtendedCommunityCase) {
     final TrafficMarkingExtendedCommunity trafficMarking =
         ((TrafficMarkingExtendedCommunityCase) ex).getTrafficMarkingExtendedCommunity();
     buffer.writeZero(RESERVED);
     ByteBufWriteUtil.writeUnsignedByte(
         trafficMarking.getGlobalAdministrator().getValue().shortValue(), buffer);
   } else {
     super.serializeExtendedCommunity(exCommunities, buffer);
   }
 }
Exemplo n.º 5
0
 /**
  * Serialize an object into a given byte buffer.
  *
  * @param o The object to serialize.
  * @param b The bytebuf to serialize it into.
  */
 @Override
 public void serialize(Object o, ByteBuf b) {
   String className = o == null ? "null" : o.getClass().getName();
   if (className.contains("$ByteBuddy$")) {
     String SMRClass = className.split("\\$")[0];
     className = "CorfuObject";
     byte[] classNameBytes = className.getBytes();
     b.writeShort(classNameBytes.length);
     b.writeBytes(classNameBytes);
     byte[] SMRClassNameBytes = SMRClass.getBytes();
     b.writeShort(SMRClassNameBytes.length);
     b.writeBytes(SMRClassNameBytes);
     UUID id = ((ICorfuObject) o).getStreamID();
     log.trace("Serializing a CorfuObject of type {} as a stream pointer to {}", SMRClass, id);
     b.writeLong(id.getMostSignificantBits());
     b.writeLong(id.getLeastSignificantBits());
   } else {
     byte[] classNameBytes = className.getBytes();
     b.writeShort(classNameBytes.length);
     b.writeBytes(classNameBytes);
     if (o == null) {
       return;
     }
     try (ByteBufOutputStream bbos = new ByteBufOutputStream(b)) {
       try (OutputStreamWriter osw = new OutputStreamWriter(bbos)) {
         gson.toJson(o, o.getClass(), osw);
       }
     } catch (IOException ie) {
       log.error("Exception during serialization!", ie);
     }
   }
 }
Exemplo n.º 6
0
  @Override
  protected void encode(ChannelHandlerContext chc, SubscribeMessage message, ByteBuf out) {
    if (message.subscriptions().isEmpty()) {
      throw new IllegalArgumentException("Found a subscribe message with empty topics");
    }

    if (message.getQos() != AbstractMessage.QOSType.LEAST_ONE) {
      throw new IllegalArgumentException(
          "Expected a message with QOS 1, found " + message.getQos());
    }

    ByteBuf variableHeaderBuff = chc.alloc().buffer(4);
    ByteBuf buff = null;
    try {
      variableHeaderBuff.writeShort(message.getMessageID());
      for (SubscribeMessage.Couple c : message.subscriptions()) {
        variableHeaderBuff.writeBytes(Utils.encodeString(c.topicFilter));
        variableHeaderBuff.writeByte(c.qos);
      }

      int variableHeaderSize = variableHeaderBuff.readableBytes();
      byte flags = Utils.encodeFlags(message);
      buff = chc.alloc().buffer(2 + variableHeaderSize);

      buff.writeByte(AbstractMessage.SUBSCRIBE << 4 | flags);
      buff.writeBytes(Utils.encodeRemainingLength(variableHeaderSize));
      buff.writeBytes(variableHeaderBuff);

      out.writeBytes(buff);
    } finally {
      variableHeaderBuff.release();
      buff.release();
    }
  }
 @Override
 public void encodeInto(ChannelHandlerContext ctx, ByteBuf buffer) throws IOException {
   buffer.writeInt(data.length);
   buffer.writeInt(signature.length);
   buffer.writeBytes(data);
   buffer.writeBytes(signature);
 }
Exemplo n.º 8
0
 private static ByteBuf encodeHeaderBlock(int version, SpdyHeaderBlock headerFrame)
     throws Exception {
   Set<String> names = headerFrame.getHeaderNames();
   int numHeaders = names.size();
   if (numHeaders == 0) {
     return Unpooled.EMPTY_BUFFER;
   }
   if (numHeaders > SPDY_MAX_NV_LENGTH) {
     throw new IllegalArgumentException("header block contains too many headers");
   }
   ByteBuf headerBlock = Unpooled.buffer();
   writeLengthField(version, headerBlock, numHeaders);
   for (String name : names) {
     byte[] nameBytes = name.getBytes("UTF-8");
     writeLengthField(version, headerBlock, nameBytes.length);
     headerBlock.writeBytes(nameBytes);
     int savedIndex = headerBlock.writerIndex();
     int valueLength = 0;
     writeLengthField(version, headerBlock, valueLength);
     for (String value : headerFrame.getHeaders(name)) {
       byte[] valueBytes = value.getBytes("UTF-8");
       headerBlock.writeBytes(valueBytes);
       headerBlock.writeByte(0);
       valueLength += valueBytes.length + 1;
     }
     valueLength--;
     if (valueLength > SPDY_MAX_NV_LENGTH) {
       throw new IllegalArgumentException("header exceeds allowable length: " + name);
     }
     setLengthField(version, headerBlock, savedIndex, valueLength);
     headerBlock.writerIndex(headerBlock.writerIndex() - 1);
   }
   return headerBlock;
 }
 @Test
 public void testDecode() {
   ByteBuf buffer = Unpooled.buffer();
   // header
   buffer.writeByte(0);
   buffer.writeShort(1);
   buffer.writeByte(Integer.valueOf(240).byteValue());
   buffer.writeInt(44);
   buffer.writeLong(1);
   buffer.writeLong(2);
   // attributes
   buffer.writeShort(4);
   buffer.writeInt(4);
   buffer.writeBytes("luo!".getBytes());
   buffer.writeShort(5);
   buffer.writeInt(4);
   buffer.writeBytes("luo!".getBytes());
   MockRelayMessage message =
       (MockRelayMessage) MessageFactory.getInstance().createMessage(buffer);
   Assert.assertEquals(message.version(), GenericMessage.VERSION);
   Assert.assertEquals(message.length(), Unsigned32.get(44L));
   Assert.assertEquals(message.flag().get().isGroup(), true);
   Assert.assertEquals(message.flag().get().isRequest(), true);
   Assert.assertEquals(message.flag().get().isProxiable(), true);
   Assert.assertEquals(message.flag().get().isError(), true);
   assertEquals(message.code(), Unsigned16.get(1));
   assertEquals(message.hopByHop(), Integer64.get(1L));
   assertEquals(message.endToEnd(), Integer64.get(2L));
   Assert.assertEquals(message.attribute(Unsigned16.get(4)).length(), Unsigned32.get(4L));
   assertEquals(message.attribute(Unsigned16.get(4)).data().get(), "luo!");
   Assert.assertEquals(message.attribute(Unsigned16.get(5)).length(), Unsigned32.get(4L));
   assertEquals(message.attribute(Unsigned16.get(5)).data().get(), "luo!");
 }
 @Override
 public void toBytes(ByteBuf buffer) {
   buffer.writeInt(this.owner.length());
   buffer.writeBytes(this.owner.getBytes());
   buffer.writeInt(this.notifier.length());
   buffer.writeBytes(this.notifier.getBytes());
 }
Exemplo n.º 11
0
 /**
  * Adds a fragment to the block.
  *
  * @param fragment the fragment of the headers block to be added.
  * @param alloc allocator for new blocks if needed.
  * @param endOfHeaders flag indicating whether the current frame is the end of the headers. This
  *     is used for an optimization for when the first fragment is the full block. In that case,
  *     the buffer is used directly without copying.
  */
 final void addFragment(ByteBuf fragment, ByteBufAllocator alloc, boolean endOfHeaders)
     throws Http2Exception {
   if (headerBlock == null) {
     if (fragment.readableBytes() > headersDecoder.configuration().maxHeaderSize()) {
       headerSizeExceeded();
     }
     if (endOfHeaders) {
       // Optimization - don't bother copying, just use the buffer as-is. Need
       // to retain since we release when the header block is built.
       headerBlock = fragment.retain();
     } else {
       headerBlock = alloc.buffer(fragment.readableBytes());
       headerBlock.writeBytes(fragment);
     }
     return;
   }
   if (headersDecoder.configuration().maxHeaderSize() - fragment.readableBytes()
       < headerBlock.readableBytes()) {
     headerSizeExceeded();
   }
   if (headerBlock.isWritable(fragment.readableBytes())) {
     // The buffer can hold the requested bytes, just write it directly.
     headerBlock.writeBytes(fragment);
   } else {
     // Allocate a new buffer that is big enough to hold the entire header block so far.
     ByteBuf buf = alloc.buffer(headerBlock.readableBytes() + fragment.readableBytes());
     buf.writeBytes(headerBlock);
     buf.writeBytes(fragment);
     headerBlock.release();
     headerBlock = buf;
   }
 }
  public ByteBuf encode(ByteBuf buf, EncryptionKeyResponseMessage message) throws IOException {
    ByteBufUtils.writeVarInt(buf, message.getSharedSecret().length);
    buf.writeBytes(message.getSharedSecret());

    ByteBufUtils.writeVarInt(buf, message.getVerifyToken().length);
    buf.writeBytes(message.getVerifyToken());
    return buf;
  }
Exemplo n.º 13
0
 private static void encodeHeader(ByteBuf buf, String header, String value) {
   buf.writeBytes(header.getBytes(CharsetUtil.US_ASCII));
   buf.writeByte(COLON);
   buf.writeByte(SP);
   buf.writeBytes(value.getBytes(CharsetUtil.US_ASCII));
   buf.writeByte(CR);
   buf.writeByte(LF);
 }
 @SuppressWarnings("unchecked")
 private void writeMetric(String json, HttpServerResponse<O> response) {
   byte[] bytes = json.getBytes(Charset.defaultCharset());
   ByteBuf byteBuf = UnpooledByteBufAllocator.DEFAULT.buffer(bytes.length + EXTRA_SPACE);
   byteBuf.writeBytes(HEADER);
   byteBuf.writeBytes(bytes);
   byteBuf.writeBytes(FOOTER);
   response.writeAndFlush((O) byteBuf);
 }
 @Override
 public void toBytes(ByteBuf buf) {
   buf.writeInt(x);
   buf.writeInt(y);
   buf.writeInt(z);
   buf.writeByte(orientation);
   buf.writeByte(state);
   buf.writeInt(customName.length());
   buf.writeBytes(customName.getBytes());
   buf.writeInt(owner.length());
   buf.writeBytes(owner.getBytes());
 }
  private ByteBuf constructResponseExec(ExecutionHandlerContext context) {
    Queue<Command> cQ = context.getTransactionQueue();
    ByteBuf response = context.getByteBufAllocator().buffer();
    response.writeByte(Coder.ARRAY_ID);
    response.writeBytes(Coder.intToBytes(cQ.size()));
    response.writeBytes(Coder.CRLFar);

    for (Command c : cQ) {
      ByteBuf r = c.getResponse();
      response.writeBytes(r);
    }
    return response;
  }
  public void encodeJsonP(
      Integer jsonpIndex, Queue<Packet> packets, ByteBuf out, ByteBufAllocator allocator, int limit)
      throws IOException {
    boolean jsonpMode = jsonpIndex != null;

    ByteBuf buf = allocateBuffer(allocator);

    int i = 0;
    while (true) {
      Packet packet = packets.poll();
      if (packet == null || i == limit) {
        break;
      }

      ByteBuf packetBuf = allocateBuffer(allocator);
      encodePacket(packet, packetBuf, allocator, true);

      int packetSize = packetBuf.writerIndex();
      buf.writeBytes(toChars(packetSize));
      buf.writeBytes(B64_DELIMITER);
      buf.writeBytes(packetBuf);

      packetBuf.release();

      i++;

      for (ByteBuf attachment : packet.getAttachments()) {
        ByteBuf encodedBuf = Base64.encode(attachment, Base64Dialect.URL_SAFE);
        buf.writeBytes(toChars(encodedBuf.readableBytes() + 2));
        buf.writeBytes(B64_DELIMITER);
        buf.writeBytes(BINARY_HEADER);
        buf.writeBytes(encodedBuf);
      }
    }

    if (jsonpMode) {
      out.writeBytes(JSONP_HEAD);
      out.writeBytes(toChars(jsonpIndex));
      out.writeBytes(JSONP_START);
    }

    processUtf8(buf, out, jsonpMode);
    buf.release();

    if (jsonpMode) {
      out.writeBytes(JSONP_END);
    }
  }
  private void sendServerError(final ChannelHandlerContext ctx, final ServerException cause)
      throws Exception {

    if (ctx.channel().isActive()) {

      final ByteBuf content = Unpooled.buffer();

      content.writeBytes(
          (cause.getStatus().code()
                  + " "
                  + cause.getStatus().reasonPhrase()
                  + " - "
                  + cause.getMessage())
              .getBytes());

      final FullHttpResponse response =
          new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, cause.getStatus());

      response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes());

      response.content().writeBytes(content);

      ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
  }
Exemplo n.º 19
0
 @Override
 public void toBytes(ByteBuf buf) {
   if (buffer == null) {
     buffer = new PacketBuffer(Unpooled.buffer());
   }
   buf.writeBytes(buffer);
 }
Exemplo n.º 20
0
 /**
  * Appends the specified {@code Buffer} to the end of this Buffer. The buffer will expand as
  * necessary to accommodate any bytes written.
  *
  * <p>Returns a reference to {@code this} so multiple operations can be appended together.
  */
 public Buffer appendBuffer(Buffer buff) {
   ByteBuf cb = buff.getByteBuf();
   buffer.writeBytes(buff.getByteBuf());
   cb.readerIndex(
       0); // Need to reset readerindex since Netty write modifies readerIndex of source!
   return this;
 }
Exemplo n.º 21
0
 private void sendMessage(ChannelHandlerContext ctx, String config) {
   byte[] bytes = config.getBytes(charset);
   ByteBuf message = Unpooled.buffer(4 + bytes.length);
   message.writeInt(bytes.length);
   message.writeBytes(bytes);
   ctx.writeAndFlush(message);
 }
Exemplo n.º 22
0
  @Override
  protected void encode(ChannelHandlerContext ctx, GamePacket msg, List<Object> out) {
    PacketType type = msg.getType();
    int headerLength = 1;
    int payloadLength = msg.getLength();

    if (type == PacketType.VARIABLE_BYTE) {
      headerLength++;
      if (payloadLength >= 256) {
        throw new IllegalStateException("Payload too long for variable byte packet");
      }
    } else if (type == PacketType.VARIABLE_SHORT) {
      headerLength += 2;
      if (payloadLength >= 65536) {
        throw new IllegalStateException("Payload too long for variable short packet");
      }
    }

    ByteBuf buffer = Unpooled.buffer(headerLength + payloadLength);
    buffer.writeByte((msg.getOpcode() + random.nextInt()) & 0xFF);

    if (type == PacketType.VARIABLE_BYTE) {
      buffer.writeByte(payloadLength);
    } else if (type == PacketType.VARIABLE_SHORT) {
      buffer.writeShort(payloadLength);
    }

    out.add(buffer.writeBytes(msg.getPayload()));
  }
Exemplo n.º 23
0
 protected void writeContent(StompFrame frame, ByteBuf buffer) {
   if (frame instanceof StompContentFrame) {
     ByteBuf content = ((StompContentFrame) frame).content();
     buffer.writeBytes(content);
   }
   buffer.writeByte(NULL);
 }
Exemplo n.º 24
0
  public ByteBuf readChunk(ChannelHandlerContext var1) throws Exception {
    long var2 = this.offset;
    if (var2 >= this.endOffset) {
      return null;
    } else {
      int var4 = (int) Math.min((long) this.chunkSize, this.endOffset - var2);
      ByteBuf var5 = var1.alloc().buffer(var4);
      boolean var6 = true;

      try {
        int var7 = 0;

        while (true) {
          int var8 = var5.writeBytes((ScatteringByteChannel) this.in, var4 - var7);
          if (var8 >= 0) {
            var7 += var8;
            if (var7 != var4) {
              continue;
            }
          }

          this.offset += (long) var7;
          var6 = false;
          ByteBuf var12 = var5;
          return var12;
        }
      } finally {
        if (var6) {
          var5.release();
        }
      }
    }
  }
Exemplo n.º 25
0
  public ByteBuf encode(NettyMessage msg) throws Exception {
    ByteBuf sendBuf = Unpooled.buffer();
    sendBuf.writeInt((msg.getHeader().getCrcCode()));
    sendBuf.writeInt((msg.getHeader().getLength()));
    sendBuf.writeLong((msg.getHeader().getSessionID()));
    sendBuf.writeByte((msg.getHeader().getType()));
    sendBuf.writeByte((msg.getHeader().getPriority()));
    sendBuf.writeInt((msg.getHeader().getAttachment().size()));
    String key = null;
    byte[] keyArray = null;
    Object value = null;

    for (Map.Entry<String, Object> param : msg.getHeader().getAttachment().entrySet()) {
      key = param.getKey();
      keyArray = key.getBytes("UTF-8");
      sendBuf.writeInt(keyArray.length);
      sendBuf.writeBytes(keyArray);
      value = param.getValue();
      marshallingEncoder.encode(value, sendBuf);
    }
    key = null;
    keyArray = null;
    value = null;
    if (msg.getBody() != null) {
      marshallingEncoder.encode(msg.getBody(), sendBuf);
    } else sendBuf.writeInt(0);
    sendBuf.setInt(4, sendBuf.readableBytes());
    return sendBuf;
  }
Exemplo n.º 26
0
 @Override
 public MessageBuffer<ByteBuf> writeStrings(String... messages) {
   ByteBuf strMultiBuf = NettyUtils.writeStrings(messages);
   buffer.writeBytes(strMultiBuf);
   strMultiBuf.release();
   return this;
 }
Exemplo n.º 27
0
  /**
   * 发送消息
   *
   * @param message
   * @param msg
   */
  public void send(final Payload message, final byte[] msg) {
    try {

      final ByteBuf data = context.alloc().buffer(msg.length); // (2)
      data.writeBytes(msg);

      final ChannelFuture cf = context.writeAndFlush(data);
      cf.addListener(
          new GenericFutureListener<Future<? super Void>>() {
            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
              if (cf.cause() != null) {
                logger.error("{}, Send Error.", context, cf.cause());
                PayloadServiceImpl.instance.updateSendStatus(
                    message,
                    userId,
                    new PushStatus(PushStatus.WriterError, cf.cause().getMessage()));
              } else {
                updateOpTime();
                PayloadServiceImpl.instance.updateSendStatus(
                    message, userId, new PushStatus(PushStatus.Success));
                ClientServiceImpl.instance.updateBadge(userId, 1);
                if (logger.isDebugEnabled()) {
                  logger.debug("Send Done, userId={}, messageId={}", userId, message.getId());
                }
              }
            }
          });

    } catch (Exception e) {
      message.setStatus(userId, new PushStatus(PushStatus.UnKnown, e.getMessage()));
      logger.error(e.getMessage(), e);
    }
  }
Exemplo n.º 28
0
    /**
     * Reads the content of the entry into a new buffer. Use {@link #readContent(ByteBufAllocator,
     * InputStream, int)} when the length of the stream is known.
     */
    protected ByteBuf readContent(ByteBufAllocator alloc, InputStream in) throws IOException {
      ByteBuf buf = null;
      boolean success = false;
      try {
        buf = alloc.directBuffer();
        for (; ; ) {
          if (buf.writeBytes(in, 8192) < 0) {
            break;
          }
        }

        success = true;

        if (buf.isReadable()) {
          return buf;
        } else {
          buf.release();
          return Unpooled.EMPTY_BUFFER;
        }
      } finally {
        if (!success && buf != null) {
          buf.release();
        }
      }
    }
Exemplo n.º 29
0
 void encode(ByteBuf buf) {
   if (bytes == null) {
     HttpHeaders.encodeAscii0(name, buf);
   } else {
     buf.writeBytes(bytes);
   }
 }
Exemplo n.º 30
0
    /**
     * Reads the content of the entry into a new buffer. Use {@link #readContent(ByteBufAllocator,
     * InputStream)} when the length of the stream is unknown.
     */
    protected ByteBuf readContent(ByteBufAllocator alloc, InputStream in, int length)
        throws IOException {
      if (length == 0) {
        return Unpooled.EMPTY_BUFFER;
      }

      ByteBuf buf = null;
      boolean success = false;
      try {
        buf = alloc.directBuffer(length);

        int remaining = length;
        for (; ; ) {
          final int readBytes = buf.writeBytes(in, remaining);
          if (readBytes < 0) {
            break;
          }
          remaining -= readBytes;
          if (remaining <= 0) {
            break;
          }
        }

        success = true;
        return buf;
      } finally {
        if (!success && buf != null) {
          buf.release();
        }
      }
    }