当前位置: 首页>>代码示例>>Java>>正文


Java ByteBufUtil类代码示例

本文整理汇总了Java中io.netty.buffer.ByteBufUtil的典型用法代码示例。如果您正苦于以下问题:Java ByteBufUtil类的具体用法?Java ByteBufUtil怎么用?Java ByteBufUtil使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


ByteBufUtil类属于io.netty.buffer包,在下文中一共展示了ByteBufUtil类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: encode

import io.netty.buffer.ByteBufUtil; //导入依赖的package包/类
@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);
}
 
开发者ID:rodbate,项目名称:fastdfs-spring-boot,代码行数:18,代码来源:FileDownloadEncoder.java

示例2: encode

import io.netty.buffer.ByteBufUtil; //导入依赖的package包/类
@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));
}
 
开发者ID:veritasware,项目名称:neto,代码行数:17,代码来源:NetoMessageToJsonEncoder.java

示例3: processTRAILER

import io.netty.buffer.ByteBufUtil; //导入依赖的package包/类
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 ();
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:23,代码来源:FrameCodec.java

示例4: encode

import io.netty.buffer.ByteBufUtil; //导入依赖的package包/类
@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);
}
 
开发者ID:warlock-china,项目名称:azeroth,代码行数:18,代码来源:FileDownloadEncoder.java

示例5: encode

import io.netty.buffer.ByteBufUtil; //导入依赖的package包/类
@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();
    }
  }
}
 
开发者ID:HubSpot,项目名称:NioSmtpClient,代码行数:25,代码来源:Utf8SmtpRequestEncoder.java

示例6: toString

import io.netty.buffer.ByteBufUtil; //导入依赖的package包/类
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();
}
 
开发者ID:int08h,项目名称:nearenough,代码行数:24,代码来源:RtMessage.java

示例7: format

import io.netty.buffer.ByteBufUtil; //导入依赖的package包/类
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();
}
 
开发者ID:aws,项目名称:aws-sdk-java-v2,代码行数:20,代码来源:LoggingHandler.java

示例8: encode

import io.netty.buffer.ByteBufUtil; //导入依赖的package包/类
@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()));
    });
}
 
开发者ID:PocketServer,项目名称:PocketServer,代码行数:21,代码来源:PocketWrapperEncoder.java

示例9: toByteArray

import io.netty.buffer.ByteBufUtil; //导入依赖的package包/类
/**
 * 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 */}
	}
}
 
开发者ID:nickman,项目名称:HeliosStreams,代码行数:26,代码来源:StreamedMetricAggregation.java

示例10: toByteArray

import io.netty.buffer.ByteBufUtil; //导入依赖的package包/类
/**
 * 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 */}
	}
}
 
开发者ID:nickman,项目名称:HeliosStreams,代码行数:23,代码来源:StreamedMetricValue.java

示例11: certificateRejected

import io.netty.buffer.ByteBufUtil; //导入依赖的package包/类
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);
    }
}
 
开发者ID:eclipse,项目名称:milo,代码行数:25,代码来源:DefaultCertificateValidator.java

示例12: encode

import io.netty.buffer.ByteBufUtil; //导入依赖的package包/类
@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);
    }
}
 
开发者ID:ribasco,项目名称:async-gamequery-lib,代码行数:18,代码来源:SourceRconRequestEncoder.java

示例13: channelRead0

import io.netty.buffer.ByteBufUtil; //导入依赖的package包/类
@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);
    }
}
 
开发者ID:cowthan,项目名称:JavaAyo,代码行数:23,代码来源:HelloWorldHttp1Handler.java

示例14: fromDataString

import io.netty.buffer.ByteBufUtil; //导入依赖的package包/类
/**
 * 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);
}
 
开发者ID:SecureSmartHome,项目名称:SecureSmartHome,代码行数:25,代码来源:DeviceConnectInformation.java

示例15: onErrorWhenGettingNodeOne

import io.netty.buffer.ByteBufUtil; //导入依赖的package包/类
@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));
}
 
开发者ID:ordina-jworks,项目名称:microservices-dashboard-server,代码行数:19,代码来源:PactsAggregatorTest.java


注:本文中的io.netty.buffer.ByteBufUtil类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。