本文整理匯總了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);
}
示例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));
}
示例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 ();
}
示例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);
}
示例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();
}
}
}
示例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();
}
示例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();
}
示例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()));
});
}
示例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 */}
}
}
示例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 */}
}
}
示例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);
}
}
示例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);
}
}
示例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);
}
}
示例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);
}
示例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));
}