Java 类io.netty.buffer.ByteBufUtil 实例源码

项目:fastdfs-spring-boot    文件:FileDownloadEncoder.java   
@Override
public List<Object> encode(ByteBufAllocator alloc) {
    byte[] pathBytes = fileId.pathBytes();
    int length = 2 * FDFS_LONG_LEN + FDFS_GROUP_LEN + pathBytes.length;
    byte cmd = FILE_DOWNLOAD;

    ByteBuf buf = alloc.buffer(length + FDFS_HEAD_LEN);
    buf.writeLong(length);
    buf.writeByte(cmd);
    buf.writeByte(ERRNO_OK);

    buf.writeLong(offset);
    buf.writeLong(size);
    writeFixLength(buf, fileId.group(), FDFS_GROUP_LEN);
    ByteBufUtil.writeUtf8(buf, fileId.path());
    return Collections.singletonList(buf);
}
项目:neto    文件:NetoMessageToJsonEncoder.java   
@Override
protected void encode(ChannelHandlerContext ctx, NetoJsonMessage msg, List<Object> out) throws Exception {

    if (opcodeMap != null) {
        Integer opcode = opcodeMap.inverse().get(msg.getClass());
        msg.setOpcode(opcode);
    }

    String result = objectMapper.writeValueAsString(msg) + "\n";

    if (result.length() == 0) {
        return;
    }

    out.add(ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(result), charset));
}
项目:neoscada    文件:FrameCodec.java   
private void processTRAILER ( final ChannelHandlerContext ctx, final byte b, final ByteBuf msg )
{
    if ( b != Constants.LF )
    {
        throw new CodecException ( String.format ( "Expected trailer byte (LF) but found 0x%02X: Remaining buffer: %s", b, ByteBufUtil.hexDump ( msg, msg.readerIndex (), msg.readableBytes () ) ) );
    }

    final int length = ctx.attr ( ATTR_EXPECTED_LENGTH ).get ();
    final long txnr = Long.parseLong ( ctx.attr ( ATTR_TXNR_BUFFER ).get ().toString ( TXNR_CHARSET ) );
    final String command = ctx.attr ( ATTR_COMMAND_BUFFER ).get ().toString ( COMMAND_CHARSET );
    final ByteBuf data = ctx.attr ( ATTR_DATA_BUFFER ).get ().readSlice ( length );

    final Frame frame = new Frame ( txnr, command, data );

    ctx.fireChannelRead ( frame );

    ctx.attr ( ATTR_STATE ).set ( State.TXNR );
    ctx.attr ( ATTR_TXNR_BUFFER ).get ().clear ();
    ctx.attr ( ATTR_COMMAND_BUFFER ).get ().clear ();
    ctx.attr ( ATTR_LENGTH_BUFFER ).get ().clear ();
    ctx.attr ( ATTR_DATA_BUFFER ).get ().clear ();
}
项目:azeroth    文件:FileDownloadEncoder.java   
@Override
public List<Object> encode(ByteBufAllocator alloc) {
    byte[] pathBytes = fileId.pathBytes();
    int length = 2 * FDFS_LONG_LEN + FDFS_GROUP_LEN + pathBytes.length;
    byte cmd = FastdfsConstants.Commands.FILE_DOWNLOAD;

    ByteBuf buf = alloc.buffer(length + FDFS_HEAD_LEN);
    buf.writeLong(length);
    buf.writeByte(cmd);
    buf.writeByte(ERRNO_OK);

    buf.writeLong(offset);
    buf.writeLong(size);
    writeFixLength(buf, fileId.group(), FDFS_GROUP_LEN);
    ByteBufUtil.writeUtf8(buf, fileId.path());
    return Collections.singletonList(buf);
}
项目:NioSmtpClient    文件:Utf8SmtpRequestEncoder.java   
@Override
protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
  if (!(msg instanceof SmtpRequest)) {
    return;
  }

  boolean release = true;
  final ByteBuf buffer = ctx.alloc().buffer();

  try {
    final SmtpRequest req = (SmtpRequest) msg;

    ByteBufUtil.writeAscii(buffer, req.command().name());
    writeParameters(req.parameters(), buffer);
    buffer.writeBytes(CRLF);

    out.add(buffer);
    release = false;
  } finally {
    if (release) {
      buffer.release();
    }
  }
}
项目:nearenough    文件:RtMessage.java   
public String toString(int indentLevel) {
  char[] indent1 = new char[2 * (indentLevel - 1)];
  char[] indent2 = new char[2 * indentLevel];
  Arrays.fill(indent1, ' ');
  Arrays.fill(indent2, ' ');

  StringBuilder sb = new StringBuilder("RtMessage|").append(numTags).append("|{\n");

  if (map != null) {
    map.forEach(
        (tag, value) -> {
          sb.append(indent2).append(tag.name()).append("(").append(value.length).append(") = ");
          if (tag.isNested()) {
            sb.append(fromBytes(value).toString(indentLevel + 1));
          } else {
            sb.append(ByteBufUtil.hexDump(value)).append('\n');
          }
        }
    );
  }
  sb.append(indent1).append("}\n");
  return sb.toString();
}
项目:aws-sdk-java-v2    文件:LoggingHandler.java   
private String format(ChannelHandlerContext ctx, String event, Object obj) {
    StringBuilder sb = new StringBuilder(ctx.channel().toString()).append(" ").append(event);
    if (obj instanceof ByteBuf) {
        ByteBuf buf = (ByteBuf) obj;
        sb.append(" ").append(buf.readableBytes()).append(" bytes\n").append(ByteBufUtil.prettyHexDump(buf));
    } else if (obj instanceof ByteBufHolder) {
        ByteBufHolder holder = (ByteBufHolder) obj;
        sb.append(" ")
            .append(holder.content().readableBytes())
            .append(" bytes\n")
            .append(String.valueOf(obj))
            .append("\n")
            .append(ByteBufUtil.prettyHexDump(holder.content()));
    } else {
        sb.append("\n").append(String.valueOf(obj));
    }

    return sb.toString();
}
项目:fastdfs-client    文件:FileDownloadEncoder.java   
@Override
public List<Object> encode(ByteBufAllocator alloc) {
    byte[] pathBytes = fileId.pathBytes();
    int length = 2 * FDFS_LONG_LEN + FDFS_GROUP_LEN + pathBytes.length;
    byte cmd = FastdfsConstants.Commands.FILE_DOWNLOAD;

    ByteBuf buf = alloc.buffer(length + FDFS_HEAD_LEN);
    buf.writeLong(length);
    buf.writeByte(cmd);
    buf.writeByte(ERRNO_OK);

    buf.writeLong(offset);
    buf.writeLong(size);
    writeFixLength(buf, fileId.group(), FDFS_GROUP_LEN);
    ByteBufUtil.writeUtf8(buf, fileId.path());
    return Collections.singletonList(buf);
}
项目:fastdfs-spring-boot    文件:FileDownloadEncoder.java   
@Override
public List<Object> encode(ByteBufAllocator alloc) {
    byte[] pathBytes = fileId.pathBytes();
    int length = 2 * FDFS_LONG_LEN + FDFS_GROUP_LEN + pathBytes.length;
    byte cmd = FILE_DOWNLOAD;

    ByteBuf buf = alloc.buffer(length + FDFS_HEAD_LEN);
    buf.writeLong(length);
    buf.writeByte(cmd);
    buf.writeByte(ERRNO_OK);

    buf.writeLong(offset);
    buf.writeLong(size);
    writeFixLength(buf, fileId.group(), FDFS_GROUP_LEN);
    ByteBufUtil.writeUtf8(buf, fileId.path());
    return Collections.singletonList(buf);
}
项目:PocketServer    文件:PocketWrapperEncoder.java   
@Override
protected void encode(ChannelHandlerContext ctx, PacketWrapper msg, List<Object> out) throws Exception {
    ctx.attr(PipelineUtil.ADDRESS_ATTRIBUTE).set(msg.getRecipient());
    if (msg.getPacket().getType().isRaw()) {
        ctx.write(msg.getPacket());
        return;
    }
    PacketRaknetOutCustomPacket.writeMany(ctx, msg).forEach(outgoing -> {
        ByteBuf buffer = outgoing.getBuffer();
        if (PocketEncoder.dump) {
            PocketServer.getInstance().getLogger().debug("Encoded: {}", ByteBufUtil.hexDump(buffer).toUpperCase());
        }
        Consumer<Session> receipt = msg.getAckReceipt();
        if (receipt != null) {
            Session session = PocketServer.getInstance().getSessions().get(msg.getRecipient());
            session.addAckReceipt(outgoing.getSequenceNumber(), receipt);
        }
        out.add(new DatagramPacket(buffer, msg.getRecipient()));
    });
}
项目:jeesuite-libs    文件:FileDownloadEncoder.java   
@Override
public List<Object> encode(ByteBufAllocator alloc) {
    byte[] pathBytes = fileId.pathBytes();
    int length = 2 * FDFS_LONG_LEN + FDFS_GROUP_LEN + pathBytes.length;
    byte cmd = FastdfsConstants.Commands.FILE_DOWNLOAD;

    ByteBuf buf = alloc.buffer(length + FDFS_HEAD_LEN);
    buf.writeLong(length);
    buf.writeByte(cmd);
    buf.writeByte(ERRNO_OK);

    buf.writeLong(offset);
    buf.writeLong(size);
    writeFixLength(buf, fileId.group(), FDFS_GROUP_LEN);
    ByteBufUtil.writeUtf8(buf, fileId.path());
    return Collections.singletonList(buf);
}
项目:HeliosStreams    文件:StreamedMetricAggregation.java   
/**
 * Returns this aggregation as a byte array
 * @return a byte array
 */
public byte[] toByteArray() {
    final ByteBuf b = BufferManager.getInstance().buffer(size==-1 ? 128 : size);
    try {
        b.writeByte(sticky ? 1 : 0);
        b.writeByte(doubleType ? 1 : 0);
        b.writeLong(createTime);
        b.writeLong(period);
        b.writeByte(periodUnit.ordinal());
        values.position(0);
        b.writeBytes(values);
        b.writeByte(tags.size());
        BufferManager.writeUTF(metricName, b);
        for(Map.Entry<String, String> entry: tags.entrySet()) {
            BufferManager.writeUTF(entry.getKey(), b);
            BufferManager.writeUTF(entry.getValue(), b);
        }
        return ByteBufUtil.getBytes(b);
    } finally {
        try { b.release(); } catch (Exception x) {/* No Op */}
    }
}
项目:HeliosStreams    文件:StreamedMetricValue.java   
/**
 * Returns a byte array containing the serialized streammetric
 * @return a byte array 
 */
@Override
public byte[] toByteArray() {
    final ByteBuf buff = BufferManager.getInstance().directBuffer(byteSize);
    try {
        buff.writeByte(TYPE_CODE);
        writeByteArray(buff);
        if(isDoubleValue) {
            buff.writeByte(0);
            buff.writeDouble(doubleValue);
        } else {
            buff.writeByte(1);
            buff.writeLong(longValue);
        }
        return ByteBufUtil.getBytes(buff, 0, buff.readableBytes());
    } finally {
        try { buff.release(); } catch (Exception x) {/* No Op */}
    }
}
项目:milo    文件:DefaultCertificateValidator.java   
private void certificateRejected(X509Certificate certificate) {
    if (rejectedDir == null) {
        return;
    }

    try {
        String[] ss = certificate.getSubjectX500Principal().getName().split(",");
        String name = ss.length > 0 ? ss[0] : certificate.getSubjectX500Principal().getName();
        String thumbprint = ByteBufUtil.hexDump(Unpooled.wrappedBuffer(DigestUtil.sha1(certificate.getEncoded())));

        String filename = String.format("%s [%s].der", URLEncoder.encode(name, "UTF-8"), thumbprint);

        File f = new File(rejectedDir.getAbsolutePath() + File.separator + filename);

        try (FileOutputStream fos = new FileOutputStream(f)) {
            fos.write(certificate.getEncoded());
            fos.flush();
        }

        logger.debug("Added rejected certificate entry: {}", filename);
    } catch (CertificateEncodingException | IOException e) {
        logger.error("Error adding rejected certificate entry.", e);
    }
}
项目:async-gamequery-lib    文件:SourceRconRequestEncoder.java   
@Override
protected void encode(ChannelHandlerContext ctx, SourceRconRequest msg, List<Object> out) throws Exception {
    ByteBuf rconRequestPacket = builder.deconstructAsBuffer((SourceRconPacket) msg.getMessage());

    if (log.isDebugEnabled()) {
        log.debug("Encoding Rcon Request: \n{}", ByteBufUtil.prettyHexDump(rconRequestPacket));
    }

    out.add(rconRequestPacket);

    //Send rcon-terminator except if it is an authentication request packet
    if (this.sendTerminatorPackets && !(msg instanceof SourceRconAuthRequest)) {
        ByteBuf terminatorPacket = builder.deconstructAsBuffer(new SourceRconTermRequestPacket());
        log.debug("Sending RCON Terminator ({} bytes): \n{}", terminatorPacket.readableBytes(), ByteBufUtil.prettyHexDump(terminatorPacket));
        out.add(terminatorPacket);
    }
}
项目:JavaAyo    文件:HelloWorldHttp1Handler.java   
@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
    if (HttpUtil.is100ContinueExpected(req)) {
        ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
    }
    boolean keepAlive = HttpUtil.isKeepAlive(req);

    ByteBuf content = ctx.alloc().buffer();
    content.writeBytes(HelloWorldHttp2Handler.RESPONSE_BYTES.duplicate());
    ByteBufUtil.writeAscii(content, " - via " + req.protocolVersion() + " (" + establishApproach + ")");

    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
    response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());

    if (!keepAlive) {
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    } else {
        response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        ctx.writeAndFlush(response);
    }
}
项目:SecureSmartHome    文件:DeviceConnectInformation.java   
/**
 * Read a DeviceConnectInformation from a Base64 encoded String, which was read from a QR Code.
 */
public static DeviceConnectInformation fromDataString(String data) throws IOException {
    final ByteBuf base64 = UnpooledByteBufAllocator.DEFAULT.heapBuffer(data.length());
    ByteBufUtil.writeAscii(base64, data);
    final ByteBuf byteBuf = decode(base64);
    if (byteBuf.readableBytes() != DATA_LENGTH) {
        throw new IOException("too many bytes encoded");
    }

    final byte[] addressData = new byte[ADDRESS_LENGTH];
    byteBuf.readBytes(addressData);
    final InetAddress address = InetAddress.getByAddress(addressData);
    final int port = byteBuf.readUnsignedShort();
    final byte[] idData = new byte[DeviceID.ID_LENGTH];
    byteBuf.readBytes(idData);
    final DeviceID id = new DeviceID(idData);
    final byte[] encodedToken = new byte[TOKEN_BASE64_LENGTH];
    byteBuf.readBytes(encodedToken);
    final byte[] token = decodeToken(new String(encodedToken));

    return new DeviceConnectInformation(address, port, id, token);
}
项目:microservices-dashboard-server    文件:PactsAggregatorTest.java   
@SuppressWarnings("unchecked")
@Test
public void onErrorWhenGettingNodeOne() {
    HttpClientResponse<ByteBuf> urlsResponse = mock(HttpClientResponse.class);
    ByteBuf byteBuf = (new PooledByteBufAllocator()).directBuffer();
    ByteBufUtil.writeUtf8(byteBuf, onePactSource);
    when(urlsResponse.getContent()).thenReturn(Observable.just(byteBuf));
    when(urlsResponse.getStatus()).thenReturn(HttpResponseStatus.OK);

    when(rxClient.submit(any(RxClient.ServerInfo.class), any(HttpClientRequest.class)))
            .thenReturn(Observable.just(urlsResponse), Observable.error(new RuntimeException()));

    TestSubscriber<Node> testSubscriber = new TestSubscriber<>();
    pactsAggregator.aggregateNodes().toBlocking().subscribe(testSubscriber);
    testSubscriber.assertError(RuntimeException.class);

    verify(publisher).publishEvent(any(SystemEvent.class));
}
项目:graylog-plugin-netflow    文件:RawNetFlowV9Packet.java   
@Override
public String toString() {
    StringBuilder sb = new StringBuilder("\n");
    sb.append(ByteBufUtil.prettyHexDump(Unpooled.wrappedBuffer(header().encode().toByteBuffer()))).append("\n");
    sb.append("\nTemplates:\n");
    templates().forEach((integer, byteBuf) -> {
        sb.append("\n").append(integer).append(":\n").append(ByteBufUtil.prettyHexDump(Unpooled.wrappedBuffer(byteBuf)));
    });
    final Map.Entry<Integer, byte[]> optionTemplate = optionTemplate();
    if (optionTemplate != null) {
        sb.append("\nOption Template:\n").append(ByteBufUtil.prettyHexDump(Unpooled.wrappedBuffer(optionTemplate.getValue())));
    }
    sb.append("\nData flows using these templates:\n");
    usedTemplates().forEach(templateId -> sb.append(templateId).append(" "));
    return sb.toString();
}
项目:graylog-plugin-netflow    文件:NetFlowV9Parser.java   
/**
 * Like above, but only retrieves the bytes and template ids
 */
public static List<Map.Entry<Integer, byte[]>> parseTemplatesShallow(ByteBuf bb) {
    final ImmutableList.Builder<Map.Entry<Integer, byte[]>> templates = ImmutableList.builder();
    int len = bb.readUnsignedShort();

    int p = 4; // flow set id and length field itself
    while (p < len) {
        final int start = bb.readerIndex();
        final int templateId = bb.readUnsignedShort();
        final int fieldCount = bb.readUnsignedShort();
        final ImmutableList.Builder<NetFlowV9FieldDef> fieldDefs = ImmutableList.builder();
        for (int i = 0; i < fieldCount; i++) {
            int fieldType = bb.readUnsignedShort();
            int fieldLength = bb.readUnsignedShort();
        }
        final byte[] bytes = ByteBufUtil.getBytes(bb, start, bb.readerIndex() - start);
        final Map.Entry<Integer, byte[]> template = Maps.immutableEntry(templateId, bytes);
        templates.add(template);

        p += 4 + fieldCount * 4;
    }

    return templates.build();
}
项目:netty4.0.27Learn    文件:HttpContentCompressorTest.java   
@Test
public void testFullContent() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new HttpContentCompressor());
    ch.writeInbound(newRequest());

    FullHttpResponse res = new DefaultFullHttpResponse(
            HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
            Unpooled.copiedBuffer("Hello, World", CharsetUtil.US_ASCII));
    res.headers().set(Names.CONTENT_LENGTH, res.content().readableBytes());
    ch.writeOutbound(res);

    assertEncodedResponse(ch);
    HttpContent c = (HttpContent) ch.readOutbound();
    assertThat(ByteBufUtil.hexDump(c.content()), is("1f8b0800000000000000f248cdc9c9d75108cf2fca4901000000ffff"));
    c.release();

    c = (HttpContent) ch.readOutbound();
    assertThat(ByteBufUtil.hexDump(c.content()), is("0300c6865b260c000000"));
    c.release();

    LastHttpContent last = (LastHttpContent) ch.readOutbound();
    assertThat(last.content().readableBytes(), is(0));
    last.release();

    assertThat(ch.readOutbound(), is(nullValue()));
}
项目:netty4.0.27Learn    文件:HttpContentCompressorTest.java   
/**
 * If the length of the content is unknown, {@link HttpContentEncoder} should not skip encoding the content
 * even if the actual length is turned out to be 0.
 */
@Test
public void testEmptySplitContent() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new HttpContentCompressor());
    ch.writeInbound(newRequest());

    ch.writeOutbound(new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK));
    assertEncodedResponse(ch);

    ch.writeOutbound(LastHttpContent.EMPTY_LAST_CONTENT);
    HttpContent chunk = (HttpContent) ch.readOutbound();
    assertThat(ByteBufUtil.hexDump(chunk.content()), is("1f8b080000000000000003000000000000000000"));
    chunk.release();

    chunk = (HttpContent) ch.readOutbound();
    assertThat(chunk.content().isReadable(), is(false));
    assertThat(chunk, is(instanceOf(LastHttpContent.class)));
    chunk.release();

    assertThat(ch.readOutbound(), is(nullValue()));
}
项目:netty4.0.27Learn    文件:FingerprintTrustManagerFactory.java   
/**
 * Creates a new instance.
 *
 * @param fingerprints a list of SHA1 fingerprints
 */
public FingerprintTrustManagerFactory(byte[]... fingerprints) {
    if (fingerprints == null) {
        throw new NullPointerException("fingerprints");
    }

    List<byte[]> list = new ArrayList<byte[]>();
    for (byte[] f: fingerprints) {
        if (f == null) {
            break;
        }
        if (f.length != SHA1_BYTE_LEN) {
            throw new IllegalArgumentException("malformed fingerprint: " +
                    ByteBufUtil.hexDump(Unpooled.wrappedBuffer(f)) + " (expected: SHA1)");
        }
        list.add(f.clone());
    }

    this.fingerprints = list.toArray(new byte[list.size()][]);
}
项目:netty4.0.27Learn    文件:AbstractEpollChannel.java   
/**
 * Returns an off-heap copy of the specified {@link ByteBuf}, and releases the specified holder.
 * The caller must ensure that the holder releases the original {@link ByteBuf} when the holder is released by
 * this method.
 */
protected final ByteBuf newDirectBuffer(Object holder, ByteBuf buf) {
    final int readableBytes = buf.readableBytes();
    if (readableBytes == 0) {
        ReferenceCountUtil.safeRelease(holder);
        return Unpooled.EMPTY_BUFFER;
    }

    final ByteBufAllocator alloc = alloc();
    if (alloc.isDirectBufferPooled()) {
        return newDirectBuffer0(holder, buf, alloc, readableBytes);
    }

    final ByteBuf directBuf = ByteBufUtil.threadLocalDirectBuffer();
    if (directBuf == null) {
        return newDirectBuffer0(holder, buf, alloc, readableBytes);
    }

    directBuf.writeBytes(buf, buf.readerIndex(), readableBytes);
    ReferenceCountUtil.safeRelease(holder);
    return directBuf;
}
项目:lambdatra    文件:StaticMiddleware.java   
@Override
public boolean call(WrappedRequest<S> req, WrappedResponse<S> res) throws IOException {
    File dest = new File(source, req.getPath());

    if (dest.exists()) {
        if (dest.isFile()) {
            serveFile(dest, res);
        } else {
            for (String i : INDICE) {
                File index = new File(dest, i);

                if (index.exists()) {
                    serveFile(index, res);
                    return true;
                }
            }

            res.setStatus(HttpResponseStatus.FORBIDDEN);
            ByteBufUtil.writeUtf8(res.getBuffer(), "FORBIDDEN");
        }

        return true;
    }

    return false;
}
项目:armeria    文件:ArmeriaMessageFramer.java   
private ByteBuf writeCompressed(ByteBuf message) throws IOException {
    CompositeByteBuf compressed = alloc.compositeBuffer();
    try (OutputStream compressingStream = compressor.compress(new ByteBufOutputStream(compressed))) {
        compressingStream.write(ByteBufUtil.getBytes(message));
    } finally {
        message.release();
    }

    int numCompressedBytes = compressed.readableBytes();
    if (maxOutboundMessageSize >= 0 && numCompressedBytes > maxOutboundMessageSize) {
        compressed.release();
        throw Status.RESOURCE_EXHAUSTED
                .withDescription(
                        String.format(
                                "message too large %d > %d", numCompressedBytes, maxOutboundMessageSize))
                .asRuntimeException();
    }

    ByteBuf header = alloc.buffer(HEADER_LENGTH);
    header.writeByte(COMPRESSED);
    header.writeInt(numCompressedBytes);
    compressed.addComponent(true, 0, header);

    return compressed;
}
项目:armeria    文件:ZlibStreamDecoder.java   
private byte[] fetchDecoderOutput() {
    CompositeByteBuf decoded = Unpooled.compositeBuffer();
    for (;;) {
        ByteBuf buf = decoder.readInbound();
        if (buf == null) {
            break;
        }
        if (!buf.isReadable()) {
            buf.release();
            continue;
        }
        decoded.addComponent(true, buf);
    }
    byte[] ret = ByteBufUtil.getBytes(decoded);
    decoded.release();
    return ret;
}
项目:armeria    文件:HttpSessionHandler.java   
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof Http2Settings) {
        // Expected
    } else {
        try {
            final String typeInfo;
            if (msg instanceof ByteBuf) {
                typeInfo = msg + " HexDump: " + ByteBufUtil.hexDump((ByteBuf) msg);
            } else {
                typeInfo = String.valueOf(msg);
            }
            throw new IllegalStateException("unexpected message type: " + typeInfo);
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}
项目:ratpack-examples    文件:KryoValueSerializer.java   
public ByteBuf serialize(Registry registry, ByteBufAllocator bufAllocator, Object value) throws Exception {
  Objects.requireNonNull(value);
  KryoPool kryoPool = registry.get(KryoPool.class);
  Kryo kryo = kryoPool.borrow();
  try {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    Output output = new Output(stream);
    kryo.writeClassAndObject(output, value);
    output.close();
    byte[] bytes = stream.toByteArray();
    String encoded = ENCODER.encodeToString(bytes);
    return ByteBufUtil.encodeString(bufAllocator, CharBuffer.wrap(encoded), CharsetUtil.UTF_8);
  } catch (Exception ex) {
    throw ex;
  } finally {
    kryoPool.release(kryo);
  }
}
项目:xio    文件:Http1ServerCodecUnitTest.java   
@Test
public void testFullRequestWithBody() throws Exception {
  outputReceived = new CountDownLatch(1);
  String payload = "body";
  ByteBuf body = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, payload);
  FullHttpRequest requestIn = new DefaultFullHttpRequest(HTTP_1_1, GET, "/", body);

  channel.writeInbound(requestIn);

  channel.runPendingTasks(); // blocks

  Uninterruptibles.awaitUninterruptibly(outputReceived);

  Request requestOut = requests.remove(0);

  assertTrue(requestOut != null);
  assertTrue(requestOut instanceof FullRequest);
  assertEquals("HTTP/1.1", requestOut.version());
  assertEquals(HttpMethod.GET, requestOut.method());
  assertEquals("/", requestOut.path());
  assertTrue(requestOut.hasBody());
  assertFalse(requestOut.body() == null);
  assertEquals(body, requestOut.body());
}
项目:xio    文件:Http1ServerCodecUnitTest.java   
@Test
public void testFullResponse() throws Exception {
  outputReceived = new CountDownLatch(2);
  ByteBuf body = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, "response");

  FullHttpRequest requestIn = new DefaultFullHttpRequest(HTTP_1_1, GET, "/");
  FullResponse responseIn = ResponseBuilders.newOk().body(body).build();

  channel.writeInbound(requestIn);
  channel.runPendingTasks(); // blocks
  channel.writeOutbound(responseIn);

  channel.runPendingTasks(); // blocks

  Uninterruptibles.awaitUninterruptibly(outputReceived);

  HttpResponse responseOut = (HttpResponse) responses.remove(0);

  assertTrue(responseOut != null);
  assertTrue(responseOut instanceof FullHttpResponse);
  assertEquals(HTTP_1_1, responseOut.protocolVersion());
  assertEquals(OK, responseOut.status());
  assertFalse(((FullHttpResponse) responseOut).content() == null);
  assertEquals(body, ((FullHttpResponse) responseOut).content());
}
项目:xio    文件:Http1ClientCodecUnitTest.java   
@Test
public void testFullRequestWithBody() throws Exception {
  outputReceived = new CountDownLatch(1);
  ByteBuf body = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, "body");
  FullRequest requestIn = RequestBuilders.newPost("/").body(body).build();

  channel.writeOutbound(requestIn);

  channel.runPendingTasks(); // blocks

  Uninterruptibles.awaitUninterruptibly(outputReceived);

  FullHttpRequest requestOut = (FullHttpRequest) requests.remove(0);

  assertTrue(requestOut != null);
  assertEquals(HTTP_1_1, requestOut.protocolVersion());
  assertEquals(HttpMethod.POST, requestOut.method());
  assertEquals("/", requestOut.uri());
  assertFalse(requestOut.content() == null);
  assertEquals(body, requestOut.content());
}
项目:xio    文件:Http1ClientCodecUnitTest.java   
@Test
public void testFullResponse() throws Exception {
  outputReceived = new CountDownLatch(1);
  ByteBuf body = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, "response");

  FullHttpResponse responseIn = new DefaultFullHttpResponse(HTTP_1_1, OK, body);

  channel.writeInbound(responseIn);

  channel.runPendingTasks(); // blocks

  Uninterruptibles.awaitUninterruptibly(outputReceived);

  Response responseOut = responses.remove(0);

  assertTrue(responseOut != null);
  assertTrue(responseOut instanceof FullResponse);
  assertEquals("HTTP/1.1", responseOut.version());
  assertEquals(OK, responseOut.status());
  assertTrue(responseOut.hasBody());
  assertFalse(responseOut.body() == null);
  assertEquals(body, responseOut.body());
}
项目:bgpcep    文件:AbstractBmpMessageWithTlvParser.java   
protected final void parseTlvs(final T builder, final ByteBuf bytes) throws BmpDeserializationException {
    Preconditions.checkArgument(bytes != null, "Array of bytes is mandatory. Can't be null.");
    if (!bytes.isReadable()) {
        return;
    }
    while (bytes.isReadable()) {
        final int type = bytes.readUnsignedShort();
        final int length = bytes.readUnsignedShort();
        if (length > bytes.readableBytes()) {
            throw new BmpDeserializationException("Wrong length specified. Passed: " + length
                    + "; Expected: <= " + bytes.readableBytes() + ".");
        }
        final ByteBuf tlvBytes = bytes.readSlice(length);
        LOG.trace("Parsing BMP TLV : {}", ByteBufUtil.hexDump(tlvBytes));

        final Tlv tlv = this.tlvRegistry.parseTlv(type, tlvBytes);
        if (tlv != null) {
            LOG.trace("Parsed BMP TLV {}.", tlv);
            addTlv(builder, tlv);
        }
    }
}
项目:bgpcep    文件:AbstractXROWithSubobjectsParser.java   
protected List<Subobject> parseSubobjects(final ByteBuf buffer) throws PCEPDeserializerException {
    Preconditions.checkArgument(buffer != null && buffer.isReadable(), "Array of bytes is mandatory. Can't be null or empty.");
    final List<Subobject> subs = new ArrayList<>();
    while (buffer.isReadable()) {
        final boolean mandatory = ((buffer.getUnsignedByte(buffer.readerIndex()) & (1 << Values.FIRST_BIT_OFFSET)) != 0) ? true : false;
        final int type = UnsignedBytes.checkedCast((buffer.readUnsignedByte() & Values.BYTE_MAX_VALUE_BYTES) & ~(1 << Values.FIRST_BIT_OFFSET));
        final int length = buffer.readUnsignedByte() - HEADER_LENGTH;
        if (length > buffer.readableBytes()) {
            throw new PCEPDeserializerException("Wrong length specified. Passed: " + length + "; Expected: <= "
                    + buffer.readableBytes());
        }
        LOG.debug("Attempt to parse subobject from bytes: {}", ByteBufUtil.hexDump(buffer));
        final Subobject sub = this.subobjReg.parseSubobject(type, buffer.readSlice(length), mandatory);
        if (sub == null) {
            LOG.warn("Unknown subobject type: {}. Ignoring subobject.", type);
        } else {
            LOG.debug("Subobject was parsed. {}", sub);
            subs.add(sub);
        }
    }
    return subs;
}
项目:bgpcep    文件:AbstractEROWithSubobjectsParser.java   
protected List<Subobject> parseSubobjects(final ByteBuf buffer) throws PCEPDeserializerException {
    // Explicit approval of empty ERO
    Preconditions.checkArgument(buffer != null, "Array of bytes is mandatory. Can't be null.");
    final List<Subobject> subs = new ArrayList<>();
    while (buffer.isReadable()) {
        final boolean loose = ((buffer.getUnsignedByte(buffer.readerIndex()) & (1 << Values.FIRST_BIT_OFFSET)) != 0) ? true : false;
        final int type = (buffer.readUnsignedByte() & Values.BYTE_MAX_VALUE_BYTES) & ~(1 << Values.FIRST_BIT_OFFSET);
        final int length = buffer.readUnsignedByte() - HEADER_LENGTH;
        if (length > buffer.readableBytes()) {
            throw new PCEPDeserializerException("Wrong length specified. Passed: " + length + "; Expected: <= "
                    + buffer.readableBytes());
        }
        LOG.debug("Attempt to parse subobject from bytes: {}", ByteBufUtil.hexDump(buffer));
        final Subobject sub = this.subobjReg.parseSubobject(type, buffer.readSlice(length), loose);
        if (sub == null) {
            LOG.warn("Unknown subobject type: {}. Ignoring subobject.", type);
        } else {
            LOG.debug("Subobject was parsed. {}", sub);
            subs.add(sub);
        }
    }
    return subs;
}
项目:bgpcep    文件:AbstractRROWithSubobjectsParser.java   
protected List<Subobject> parseSubobjects(final ByteBuf buffer) throws PCEPDeserializerException {
    Preconditions.checkArgument(buffer != null && buffer.isReadable(), "Array of bytes is mandatory. Can't be null or empty.");
    final List<Subobject> subs = new ArrayList<>();
    while (buffer.isReadable()) {
        final int type = buffer.readUnsignedByte();
        final int length = buffer.readUnsignedByte() - HEADER_LENGTH;
        if (length > buffer.readableBytes()) {
            throw new PCEPDeserializerException("Wrong length specified. Passed: " + length + "; Expected: <= "
                    + buffer.readableBytes());
        }
        LOG.debug("Attempt to parse subobject from bytes: {}", ByteBufUtil.hexDump(buffer));
        final Subobject sub = this.subobjReg.parseSubobject(type, buffer.readSlice(length));
        if (sub == null) {
            LOG.warn("Unknown subobject type: {}. Ignoring subobject.", type);
        } else {
            LOG.debug("Subobject was parsed. {}", sub);
            subs.add(sub);
        }
    }
    return subs;
}
项目:bgpcep    文件:BGPNotificationMessageParser.java   
/**
 * Serializes BGP Notification message.
 *
 * @param msg to be serialized
 * @param bytes ByteBuf where the message will be serialized
 */
@Override
public void serializeMessage(final Notification msg, final ByteBuf bytes) {
    Preconditions.checkArgument(msg instanceof Notify, "Message needs to be of type Notify");
    final Notify ntf = (Notify) msg;

    final ByteBuf msgBody = Unpooled.buffer();
    msgBody.writeByte(ntf.getErrorCode());
    msgBody.writeByte(ntf.getErrorSubcode());
    final byte[] data = ntf.getData();
    if (data != null) {
        msgBody.writeBytes(data);
    }
    LOG.trace("Notification message serialized to: {}", ByteBufUtil.hexDump(msgBody));
    MessageUtil.formatMessage(TYPE, msgBody, bytes);
}
项目:bgpcep    文件:MldpP2mpLspParser.java   
@Override
public TunnelIdentifier parse(final ByteBuf buffer) {
    final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pmsi.tunnel.rev160812.pmsi.tunnel.pmsi
            .tunnel.tunnel.identifier.mldp.p2mp.lsp.MldpP2mpLspBuilder mldpP2mpLsp =
            new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pmsi.tunnel.rev160812.pmsi.tunnel
                    .pmsi.tunnel.tunnel.identifier.mldp.p2mp.lsp.MldpP2mpLspBuilder();
    buffer.skipBytes(RESERVED);
    final Class<? extends AddressFamily> addressFamily = this.addressFamilyRegistry
            .classForFamily(buffer.readUnsignedShort());
    if (addressFamily == null) {
        LOG.debug("Skipping serialization of TunnelIdentifier {}, address family type  supported",
                ByteBufUtil.hexDump(buffer));
        return null;
    }
    mldpP2mpLsp.setAddressFamily(addressFamily);
    final short rootNodeLength = buffer.readUnsignedByte();
    mldpP2mpLsp.setRootNodeAddress(parseIpAddress(rootNodeLength, buffer.readBytes(rootNodeLength)));
    final int opaqueValueLength = buffer.readUnsignedShort();
    mldpP2mpLsp.setOpaqueValue(OpaqueUtil.parseOpaqueList(buffer.readBytes(opaqueValueLength)));
    return new MldpP2mpLspBuilder().setMldpP2mpLsp(mldpP2mpLsp.build()).build();
}
项目:bgpcep    文件:EROSubobjectListParser.java   
public List<SubobjectContainer> parseList(final ByteBuf buffer) throws RSVPParsingException {
    // Explicit approval of empty ERO
    Preconditions.checkArgument(buffer != null, "Array of bytes is mandatory. Can't be null.");
    final List<SubobjectContainer> subs = new ArrayList<>();
    while (buffer.isReadable()) {
        final boolean loose = (buffer.getUnsignedByte(buffer.readerIndex()) & (1 << Values.FIRST_BIT_OFFSET))
            != 0;
        final int type = (buffer.readUnsignedByte() & Values.BYTE_MAX_VALUE_BYTES) & ~(1 << Values
            .FIRST_BIT_OFFSET);
        final int length = buffer.readUnsignedByte() - HEADER_LENGTH;
        if (length > buffer.readableBytes()) {
            throw new RSVPParsingException("Wrong length specified. Passed: " + length + "; Expected: <= "
                + buffer.readableBytes());
        }
        LOG.debug("Attempt to parse subobject from bytes: {}", ByteBufUtil.hexDump(buffer));
        final SubobjectContainer sub = this.subobjReg.parseSubobject(type, buffer.readSlice(length), loose);
        if (sub == null) {
            LOG.warn("Unknown subobject type: {}. Ignoring subobject.", type);
        } else {
            LOG.debug("Subobject was parsed. {}", sub);
            subs.add(sub);
        }
    }
    return subs;
}