io.netty.buffer.ByteBuf Java Examples
The following examples show how to use
io.netty.buffer.ByteBuf.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GenericFrameCodecTest.java From rsocket-java with Apache License 2.0 | 6 votes |
@Test void requestResponseData() { ByteBuf request = RequestResponseFrameCodec.encode( ByteBufAllocator.DEFAULT, 1, false, null, Unpooled.copiedBuffer("d", StandardCharsets.UTF_8)); String data = RequestResponseFrameCodec.data(request).toString(StandardCharsets.UTF_8); ByteBuf metadata = RequestResponseFrameCodec.metadata(request); assertFalse(FrameHeaderCodec.hasMetadata(request)); assertEquals("d", data); assertNull(metadata); request.release(); }
Example #2
Source File: AltsTsiFrameProtector.java From grpc-nebula-java with Apache License 2.0 | 6 votes |
void protectFlush( List<ByteBuf> unprotectedBufs, Consumer<ByteBuf> ctxWrite, ByteBufAllocator alloc) throws GeneralSecurityException { checkState(crypter != null, "Cannot protectFlush after destroy."); ByteBuf protectedBuf; try { protectedBuf = handleUnprotected(unprotectedBufs, alloc); } finally { for (ByteBuf buf : unprotectedBufs) { buf.release(); } } if (protectedBuf != null) { ctxWrite.accept(protectedBuf); } }
Example #3
Source File: DefaultNettyDecoder.java From PeonyFramwork with Apache License 2.0 | 6 votes |
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> list) throws Exception { try { int readAble = in.readableBytes(); if (readAble < headSize) { return; } in.markReaderIndex(); int size = in.readInt(); if (readAble < (size + headSize)) { in.resetReaderIndex(); return; } // FIXME wjm 最好改了 try (ObjectInputStream oin = new ObjectInputStream(new ByteBufInputStream(in.readBytes(size), true))) { list.add(oin.readObject()); } } catch (Throwable e) { logger.error("decode error ", e); } }
Example #4
Source File: KcpRttExampleClient.java From java-Kcp with Apache License 2.0 | 6 votes |
@Override public void onConnected(Ukcp ukcp) { future = scheduleSrv.scheduleWithFixedDelay(() -> { ByteBuf byteBuf = rttMsg(++count); ukcp.writeOrderedReliableMessage(byteBuf); byteBuf.release(); if (count >= rtts.length) { // finish future.cancel(true); byteBuf = rttMsg(-1); ukcp.writeOrderedReliableMessage(byteBuf); byteBuf.release(); } }, 20, 20, TimeUnit.MILLISECONDS); }
Example #5
Source File: BeatsFrameDecoderTest.java From graylog-plugin-beats with GNU General Public License v3.0 | 6 votes |
private ByteBuf buildCompressedFrame(byte[] payload, int compressionLevel) { final Deflater deflater = new Deflater(compressionLevel); deflater.setInput(payload); deflater.finish(); final byte[] compressedPayload = new byte[1024]; final int compressedPayloadLength = deflater.deflate(compressedPayload); deflater.end(); final ByteBuf buffer = Unpooled.buffer(6 + compressedPayloadLength); buffer.writeByte('2'); buffer.writeByte('C'); // Compressed payload length buffer.writeInt(compressedPayloadLength); // Compressed payload buffer.writeBytes(compressedPayload, 0, compressedPayloadLength); return buffer; }
Example #6
Source File: ReqOrderAction.java From ftdc with Apache License 2.0 | 6 votes |
@Override public ByteBuf write(ByteBuf buffer) { buffer.writeBytes(brokerID); buffer.writeBytes(investorID); buffer.writeInt(orderActionRef); buffer.writeBytes(orderRef); buffer.writeInt(requestID); buffer.writeInt(frontID); buffer.writeInt(sessionID); buffer.writeBytes(exchangeID); buffer.writeBytes(orderSysID); buffer.writeBytes(actionFlag); buffer.writeDouble(limitPrice); buffer.writeInt(volumeChange); buffer.writeBytes(userID); buffer.writeBytes(instrumentID); buffer.writeBytes(investUnitID); buffer.writeBytes(iPAddress); buffer.writeBytes(macAddress); return buffer; }
Example #7
Source File: ZeroQueueConsumerImpl.java From pulsar with Apache License 2.0 | 6 votes |
@Override void receiveIndividualMessagesFromBatch(MessageMetadata msgMetadata, int redeliveryCount, List<Long> ackSet, ByteBuf uncompressedPayload, MessageIdData messageId, ClientCnx cnx) { log.warn( "Closing consumer [{}]-[{}] due to unsupported received batch-message with zero receiver queue size", subscription, consumerName); // close connection closeAsync().handle((ok, e) -> { // notify callback with failure result notifyPendingReceivedCallback(null, new PulsarClientException.InvalidMessageException( format("Unsupported Batch message with 0 size receiver queue for [%s]-[%s] ", subscription, consumerName))); return null; }); }
Example #8
Source File: AbstractPsync.java From x-pipe with Apache License 2.0 | 6 votes |
@Override public ByteBuf getRequest() { Pair<String, Long> requestInfo = getRequestMasterInfo(); replIdRequest = requestInfo.getKey(); offsetRequest = requestInfo.getValue(); if (replIdRequest == null) { replIdRequest = "?"; offsetRequest = -1; } RequestStringParser requestString = new RequestStringParser(getName(), replIdRequest, String.valueOf(offsetRequest)); if (getLogger().isDebugEnabled()) { getLogger().debug("[doRequest]{}, {}", this, StringUtil.join(" ", requestString.getPayload())); } return requestString.format(); }
Example #9
Source File: AbstractTwoOctetAsExtendedCommunityTest.java From bgpcep with Eclipse Public License 1.0 | 6 votes |
@Test public void testGetType() { final AbstractTwoOctetAsExtendedCommunity abstractTwoOctetAsExtendedCommunity = new AbstractTwoOctetAsExtendedCommunity() { @Override public void serializeExtendedCommunity(final ExtendedCommunity extendedCommunity, final ByteBuf byteAggregator) { } @Override public int getSubType() { return 0; } @Override public ExtendedCommunity parseExtendedCommunity(final ByteBuf buffer) { return null; } }; Assert.assertEquals(0, abstractTwoOctetAsExtendedCommunity.getType(true)); Assert.assertEquals(64, abstractTwoOctetAsExtendedCommunity.getType(false)); }
Example #10
Source File: MessageDecoder.java From consulo with Apache License 2.0 | 6 votes |
public static boolean readUntil(char what, @Nonnull ByteBuf buffer, @Nonnull StringBuilder builder) { int i = buffer.readerIndex(); //noinspection ForLoopThatDoesntUseLoopVariable for (int n = buffer.writerIndex(); i < n; i++) { char c = (char)buffer.getByte(i); if (c == what) { buffer.readerIndex(i + 1); return true; } else { builder.append(c); } } buffer.readerIndex(i); return false; }
Example #11
Source File: PendingWriteQueueTest.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
private static void assertWrite(ChannelHandler handler, int count) { final ByteBuf buffer = Unpooled.copiedBuffer("Test", CharsetUtil.US_ASCII); final EmbeddedChannel channel = new EmbeddedChannel(handler); channel.config().setWriteBufferLowWaterMark(1); channel.config().setWriteBufferHighWaterMark(3); ByteBuf[] buffers = new ByteBuf[count]; for (int i = 0; i < buffers.length; i++) { buffers[i] = buffer.retainedDuplicate(); } assertTrue(channel.writeOutbound(buffers)); assertTrue(channel.finish()); channel.closeFuture().syncUninterruptibly(); for (int i = 0; i < buffers.length; i++) { assertBuffer(channel, buffer); } buffer.release(); assertNull(channel.readOutbound()); }
Example #12
Source File: AddPlayerSerializer_v361.java From Protocol with Apache License 2.0 | 6 votes |
@Override public void serialize(ByteBuf buffer, AddPlayerPacket packet) { BedrockUtils.writeUuid(buffer, packet.getUuid()); BedrockUtils.writeString(buffer, packet.getUsername()); VarInts.writeLong(buffer, packet.getUniqueEntityId()); VarInts.writeUnsignedLong(buffer, packet.getRuntimeEntityId()); BedrockUtils.writeString(buffer, packet.getPlatformChatId()); BedrockUtils.writeVector3f(buffer, packet.getPosition()); BedrockUtils.writeVector3f(buffer, packet.getMotion()); BedrockUtils.writeVector3f(buffer, packet.getRotation()); BedrockUtils.writeItemData(buffer, packet.getHand()); BedrockUtils.writeEntityData(buffer, packet.getMetadata()); AdventureSettingsSerializer_v361.INSTANCE.serialize(buffer, packet.getAdventureSettings()); BedrockUtils.writeArray(buffer, packet.getEntityLinks(), BedrockUtils::writeEntityLink); BedrockUtils.writeString(buffer, packet.getDeviceId()); }
Example #13
Source File: HttpPostMultipartRequestDecoder.java From dorado with Apache License 2.0 | 5 votes |
/** * Load the field value or file data from a Multipart request * * @return {@code true} if the last chunk is loaded (boundary delimiter found), * {@code false} if need more chunks * @throws ErrorDataDecoderException */ private static boolean loadDataMultipartStandard(ByteBuf undecodedChunk, String delimiter, HttpData httpData) { final int startReaderIndex = undecodedChunk.readerIndex(); final int delimeterLength = delimiter.length(); int index = 0; int lastPosition = startReaderIndex; byte prevByte = HttpConstants.LF; boolean delimiterFound = false; while (undecodedChunk.isReadable()) { final byte nextByte = undecodedChunk.readByte(); // Check the delimiter if (prevByte == HttpConstants.LF && nextByte == delimiter.codePointAt(index)) { index++; if (delimeterLength == index) { delimiterFound = true; break; } continue; } lastPosition = undecodedChunk.readerIndex(); if (nextByte == HttpConstants.LF) { index = 0; lastPosition -= (prevByte == HttpConstants.CR) ? 2 : 1; } prevByte = nextByte; } if (prevByte == HttpConstants.CR) { lastPosition--; } ByteBuf content = undecodedChunk.copy(startReaderIndex, lastPosition - startReaderIndex); try { httpData.addContent(content, delimiterFound); } catch (IOException e) { throw new ErrorDataDecoderException(e); } undecodedChunk.readerIndex(lastPosition); return delimiterFound; }
Example #14
Source File: DcpLoggingHandler.java From java-dcp-client with Apache License 2.0 | 5 votes |
@Override protected String format(ChannelHandlerContext ctx, String eventName, Object arg) { if (arg instanceof ByteBuf) { return formatDcpPacket(ctx, eventName, (ByteBuf) arg); } else if (arg instanceof ByteBufHolder) { return formatDcpPacket(ctx, eventName, ((ByteBufHolder) arg).content()); } else { return super.format(ctx, eventName, arg); } }
Example #15
Source File: ConsumerManageProcessor.java From qmq with Apache License 2.0 | 5 votes |
private ConsumeManageRequest deserialize(ByteBuf buf) { String subject = PayloadHolderUtils.readString(buf); String consumerGroup = PayloadHolderUtils.readString(buf); int code = buf.readInt(); ConsumeManageRequest request = new ConsumeManageRequest(); request.setSubject(subject); request.setGroup(consumerGroup); request.setConsumerFromWhere(code); return request; }
Example #16
Source File: BulkInputStream.java From dremio-oss with Apache License 2.0 | 5 votes |
default void readFully(byte[] dst, int dstOffset, int dstLen) throws IOException { final ByteBuf buf1 = Unpooled.buffer(dstLen); try { readFully(buf1, dstLen); buf1.getBytes(0, dst, dstOffset, dstLen); } finally { buf1.release(); } }
Example #17
Source File: ClientCacheBlobStatusSerializer_v388.java From Protocol with Apache License 2.0 | 5 votes |
@Override public void serialize(ByteBuf buffer, ClientCacheBlobStatusPacket packet) { LongList acks = packet.getAcks(); LongList nacks = packet.getNaks(); VarInts.writeUnsignedInt(buffer, acks.size()); VarInts.writeUnsignedInt(buffer, nacks.size()); acks.forEach((LongConsumer) buffer::writeLongLE); nacks.forEach((LongConsumer) buffer::writeLongLE); }
Example #18
Source File: ChunkedReadWriteHandler.java From reef with Apache License 2.0 | 5 votes |
/** * Get expected size encoded as offset + 4 bytes of data. */ private int getSize(final byte[] data, final int offset) { if (data.length - offset < INT_SIZE) { return 0; } final ByteBuf intBuffer = Unpooled.wrappedBuffer(data, offset, INT_SIZE).order(Unpooled.LITTLE_ENDIAN); final int ret = intBuffer.readInt(); intBuffer.release(); return ret; }
Example #19
Source File: ClientCommandPacket.java From ProtocolSupportBungee with GNU Affero General Public License v3.0 | 5 votes |
@Override public Collection<ByteBuf> toData(ClientStatus packet) { if (packet.getPayload() == 1) { ByteBuf data = Allocator.allocateBuffer(); data.writeByte(LegacyPacketId.Serverbound.LOGIN_PLAY_CLIENT_COMMAND); data.writeByte(packet.getPayload()); return Collections.singletonList(data); } else { return Collections.emptyList(); } }
Example #20
Source File: ByteBufUtils.java From async-gamequery-lib with MIT License | 5 votes |
public static String readString(ByteBuf buffer, Charset encoding, boolean readNonNullTerminated, String defaultString) { int length = buffer.bytesBefore((byte) 0); if (length < 0) { if (readNonNullTerminated && buffer.readableBytes() > 0) length = buffer.readableBytes(); else return null; } String data = buffer.readCharSequence(length, encoding).toString(); //Discard the null terminator (if available) if (buffer.readableBytes() > 2 && buffer.getByte(buffer.readerIndex()) == 0) buffer.readByte(); return data; }
Example #21
Source File: UkcpServerChannel.java From kcp-netty with MIT License | 5 votes |
@Override public void out(ByteBuf data, Kcp kcp) { UkcpServerChildChannel channel = (UkcpServerChildChannel) kcp.getUser(); NioUnsafe unsafe = unsafe(); unsafe.write(UkcpPacket.newInstance(data, channel.remoteAddress()), unsafe.voidPromise()); unsafe.flush(); }
Example #22
Source File: AbstractMeasuredValueNormalized.java From neoscada with Eclipse Public License 1.0 | 5 votes |
@Override public void encode ( final ProtocolOptions options, final ByteBuf out ) { EncodeHelper.encodeHeader ( this, options, this.entries.size (), this.header, out ); for ( final InformationEntry<Double> entry : this.entries ) { entry.getAddress ().encode ( options, out ); TypeHelper.encodeNormalizedValue ( options, out, entry.getValue (), this.withTimestamp ); } }
Example #23
Source File: NettyEncoder.java From java-study with Apache License 2.0 | 5 votes |
@Override protected void encode(ChannelHandlerContext ctx, NettyMsg msg, ByteBuf out) throws Exception { if(null == msg){ throw new Exception("消息不能为空!"); } String body = msg.getBody(); byte[] bodyBytes = body.getBytes(Charset.forName("utf-8")); out.writeByte(msg.getType()); out.writeByte(msg.getFlag()); out.writeInt(bodyBytes.length); out.writeBytes(bodyBytes); }
Example #24
Source File: NettyEncoder.java From rpcx-java with Apache License 2.0 | 5 votes |
@Override public void encode(ChannelHandlerContext ctx, RemotingCommand remotingCommand, ByteBuf out) { try { byte[] data = remotingCommand.getMessage().encode(); out.writeBytes(data); } catch (Exception e) { log.error("encode exception, " + RemotingHelper.parseChannelRemoteAddr(ctx.channel()), e); if (remotingCommand != null) { log.error(remotingCommand.toString()); } RemotingUtil.closeChannel(ctx.channel()); } }
Example #25
Source File: PlaySoundSerializer_v388.java From Protocol with Apache License 2.0 | 5 votes |
@Override public void deserialize(ByteBuf buffer, PlaySoundPacket packet) { packet.setSound(BedrockUtils.readString(buffer)); packet.setPosition(BedrockUtils.readBlockPosition(buffer).toFloat().div(8)); packet.setVolume(buffer.readFloatLE()); packet.setPitch(buffer.readFloatLE()); }
Example #26
Source File: HttpInterceptor.java From cute-proxy with BSD 2-Clause "Simplified" License | 5 votes |
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (!(msg instanceof HttpObject)) { logger.debug("not http message: {}", msg.getClass().getName()); ctx.fireChannelRead(msg); return; } Http1Message message = this.httpMessage; if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; Http1ResponseHeaders responseHeader = convertHeader(response); message.responseHeader(responseHeader); Body body = responseHeader.createBody(); message.responseBody(body); } if (msg instanceof HttpContent) { ByteBuf content = ((HttpContent) msg).content(); if (content.readableBytes() > 0) { message.responseBody().append(content.nioBuffer()); } if (msg instanceof LastHttpContent) { message.responseBody().finish(); this.httpMessage = null; } } ctx.fireChannelRead(msg); }
Example #27
Source File: HttpRequestEncoderTest.java From netty4.0.27Learn with Apache License 2.0 | 5 votes |
@Test public void testQueryStringPath() throws Exception { HttpRequestEncoder encoder = new HttpRequestEncoder(); ByteBuf buffer = Unpooled.buffer(64); encoder.encodeInitialLine(buffer, new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/?url=http://example.com")); String req = buffer.toString(Charset.forName("US-ASCII")); assertEquals("GET /?url=http://example.com HTTP/1.1\r\n", req); }
Example #28
Source File: SimpleRSVPObjectRegistryTest.java From bgpcep with Eclipse Public License 1.0 | 5 votes |
@Before public void setUp() throws RSVPParsingException { MockitoAnnotations.initMocks(this); this.simpleRSVPObjectRegistry.registerRsvpObjectParser(this.subObjectTypeOne, this.subObjectCTypeOne, this.rsvpTeObjectParser); this.simpleRSVPObjectRegistry.registerRsvpObjectSerializer(SecondaryExplicitRouteObject.class, this.rsvpTeObjectSerializer); Mockito.doReturn(new SecondaryExplicitRouteObjectBuilder().build()).when(this.rsvpTeObjectParser) .parseObject(this.input); final ArgumentCaptor<RsvpTeObject> arg = ArgumentCaptor.forClass(RsvpTeObject.class); final ArgumentCaptor<ByteBuf> bufArg = ArgumentCaptor.forClass(ByteBuf.class); Mockito.doNothing().when(this.rsvpTeObjectSerializer).serializeObject(arg.capture(), bufArg.capture()); }
Example #29
Source File: BedrockUtils.java From Protocol with Apache License 2.0 | 5 votes |
public static void writeVector3i(ByteBuf buffer, Vector3i vector3i) { Preconditions.checkNotNull(buffer, "buffer"); Preconditions.checkNotNull(vector3i, "vector3i"); VarInts.writeInt(buffer, vector3i.getX()); VarInts.writeInt(buffer, vector3i.getY()); VarInts.writeInt(buffer, vector3i.getZ()); }
Example #30
Source File: LengthFieldPrependerTest.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Test public void testPrependAdjustedLength() throws Exception { final EmbeddedChannel ch = new EmbeddedChannel(new LengthFieldPrepender(4, -1)); ch.writeOutbound(msg); ByteBuf buf = ch.readOutbound(); assertEquals(4, buf.readableBytes()); assertEquals(msg.readableBytes() - 1, buf.readInt()); buf.release(); buf = ch.readOutbound(); assertSame(buf, msg); buf.release(); }