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)); }
public void write(ByteBuf buf) { buf.writeLong(this.id.getMostSignificantBits()); buf.writeLong(this.id.getLeastSignificantBits()); // rip in organize for (Object o : this.values) { switch (o.getClass().getSimpleName()) { case "String": Codec.writeString(buf, (String) o); break; case "Integer": Codec.writeVarInt32(buf, (Integer) o); break; case "Boolean": buf.writeBoolean((Boolean) o); break; default: // ignore bad developers break; } } }
public MsgEchoPeerHandler(final int messageSize) { final ByteBuf byteBuf = Unpooled.buffer(messageSize); for (int i = 0; i < byteBuf.capacity(); i++) { byteBuf.writeByte((byte) i); } message = new UdtMessage(byteBuf); }
@Override protected void doFlushByteBuffer(ByteBuf buf) throws Exception { while (buf.readable()) { doWriteBytes(buf); } buf.clear(); }
/** * 发送消息 * * @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); } }
private void handleChunk( HttpContent chunk, // final Channel channel, // final NettyResponseFuture<?> future, // AsyncHandler<?> handler) throws IOException, Exception { boolean interrupt = false; boolean last = chunk instanceof LastHttpContent; // Netty 4: the last chunk is not empty if (last) { LastHttpContent lastChunk = (LastHttpContent) chunk; HttpHeaders trailingHeaders = lastChunk.trailingHeaders(); if (!trailingHeaders.isEmpty()) { interrupt = handler.onHeadersReceived(new HttpResponseHeaders(trailingHeaders, true)) != State.CONTINUE; } } ByteBuf buf = chunk.content(); if (!interrupt && !(handler instanceof StreamedAsyncHandler) && (buf.readableBytes() > 0 || last)) { HttpResponseBodyPart part = config.getResponseBodyPartFactory().newResponseBodyPart(buf, last); interrupt = updateBodyAndInterrupt(future, handler, part); } if (interrupt || last) finishUpdate(future, channel, !last); }
@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); } }
private static void setLengthField(int version, ByteBuf buffer, int writerIndex, int length) { if (version < 3) { buffer.setShort(writerIndex, length); } else { buffer.setInt(writerIndex, length); } }
@Override public SocksRequest decode(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception { switch (state()) { case CHECK_PROTOCOL_VERSION: { version = SocksMessage.ProtocolVersion.fromByte(byteBuf.readByte()); if (version != SocksMessage.ProtocolVersion.SOCKS5) { break; } checkpoint(State.READ_AUTH_SCHEMES); } case READ_AUTH_SCHEMES: { authSchemes.clear(); authSchemeNum = byteBuf.readByte(); for (int i = 0; i < authSchemeNum; i++) { authSchemes.add(SocksMessage.AuthScheme.fromByte(byteBuf.readByte())); } msg = new SocksInitRequest(authSchemes); break; } } ctx.pipeline().remove(this); return msg; }
@Override public void toBytes(ByteBuf buf) { buf.writeInt(elementName.length()); buf.writeBytes(elementName.getBytes()); buf.writeInt(elementText.length()); buf.writeBytes(elementText.getBytes()); }
private static void writeLengthField(int version, ByteBuf buffer, int length) { if (version < 3) { buffer.writeShort(length); } else { buffer.writeInt(length); } }
@Override public void fromBytes(ByteBuf buf) { int elementNameLength = buf.readInt(); this.elementName = new String(buf.readBytes(elementNameLength).array()); int elementTextLength = buf.readInt(); this.elementText = new String(buf.readBytes(elementTextLength).array()); }
@Override public void appendMessages(Tpp tpp, Collection<MessageBatchWithRawData> batches) throws Exception { ByteBuf bodyBuf = Unpooled.buffer(); KafkaMessageBrokerSender sender = getSender(tpp.getTopic()); try { for (MessageBatchWithRawData batch : batches) { List<PartialDecodedMessage> pdmsgs = batch.getMessages(); for (PartialDecodedMessage pdmsg : pdmsgs) { m_messageCodec.encodePartial(pdmsg, bodyBuf); byte[] bytes = new byte[bodyBuf.readableBytes()]; bodyBuf.readBytes(bytes); bodyBuf.clear(); ByteBuf propertiesBuf = pdmsg.getDurableProperties(); HermesPrimitiveCodec codec = new HermesPrimitiveCodec(propertiesBuf); Map<String, String> propertiesMap = codec.readStringStringMap(); sender.send(tpp.getTopic(), propertiesMap.get("pK"), bytes); BrokerStatusMonitor.INSTANCE.kafkaSend(tpp.getTopic()); } } } finally { bodyBuf.release(); } }
private void setInput(ByteBuf decompressed) { byte[] in = new byte[decompressed.readableBytes()]; decompressed.readBytes(in); z.next_in = in; z.next_in_index = 0; z.avail_in = in.length; }
@Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf buffer) throws IOException { target = readDimensionPosFromBuffer(buffer); this.type = buffer.readInt(); this.duration = buffer.readDouble(); this.args = decodePrimitiveArrayFrom(buffer); }
@Override public OFMeterFeaturesStatsReply readFrom(ByteBuf bb) throws OFParseError { int start = bb.readerIndex(); // fixed value property version == 5 byte version = bb.readByte(); if (version != (byte) 0x5) throw new OFParseError("Wrong version: Expected=OFVersion.OF_14(5), got=" + version); // fixed value property type == 19 byte type = bb.readByte(); if (type != (byte) 0x13) throw new OFParseError("Wrong type: Expected=OFType.STATS_REPLY(19), got=" + type); int length = U16.f(bb.readShort()); if (length != 32) throw new OFParseError("Wrong length: Expected=32(32), got=" + length); if (bb.readableBytes() + (bb.readerIndex() - start) < length) { // Buffer does not have all data yet bb.readerIndex(start); return null; } if (logger.isTraceEnabled()) logger.trace("readFrom - length={}", length); long xid = U32.f(bb.readInt()); // fixed value property statsType == 11 short statsType = bb.readShort(); if (statsType != (short) 0xb) throw new OFParseError( "Wrong statsType: Expected=OFStatsType.METER_FEATURES(11), got=" + statsType); Set<OFStatsReplyFlags> flags = OFStatsReplyFlagsSerializerVer14.readFrom(bb); // pad: 4 bytes bb.skipBytes(4); OFMeterFeatures features = OFMeterFeaturesVer14.READER.readFrom(bb); OFMeterFeaturesStatsReplyVer14 meterFeaturesStatsReplyVer14 = new OFMeterFeaturesStatsReplyVer14(xid, flags, features); if (logger.isTraceEnabled()) logger.trace("readFrom - read={}", meterFeaturesStatsReplyVer14); return meterFeaturesStatsReplyVer14; }
@Override public void fromBytes(ByteBuf buf) { this.color = buf.readInt(); for (int i = 0; i < 16; i++) { String current = ""; for (int i2 = 1; i2 < 5; i++) { int currentScreen = buf.readInt(); current = current + Integer.toString(currentScreen).substring(1); } this.screen[i] = current; } /*String screenNumS; String screenData; this.screenNum = buf.readInt(); //Packet = 1<color><screenData> //Remove ^ screenNumS = Integer.toString(this.screenNum).substring(1); this.color = Integer.getInteger(screenNumS.substring(2,2)); screenData = screenNumS.substring(2); //Get the screen variable for (int i = 0;i <16;i++){ int iU = i == 0 ? 1 : i * 16; this.screen[i] = screenData.substring(iU, iU+16); }*/ }
@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())); }
@Override public void serialize(Action input, ByteBuf outBuffer) { ActionSetNshc1 action = ((ActionSetNshc1) input.getActionChoice()); serializeHeader(LENGTH, NXAST_SET_NSC_SUBTYPE, outBuffer); outBuffer.writeZero(padding); outBuffer.writeInt(action.getNxActionSetNshc1().getNshc().intValue()); }
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); }
/** * This test makes sure that even when the decoder is confronted with various chunk sizes in the * middle of decoding, it can recover and decode all the time eventually. */ @Test public void shouldHandleNonUniformNetworkBatches() { ByteBuf incoming = Unpooled.copiedBuffer(SET_REQUEST_WITH_CONTENT); while (incoming.isReadable()) { channel.writeInbound(incoming.readBytes(5)); } BinaryMemcacheRequest request = (BinaryMemcacheRequest) channel.readInbound(); assertThat(request, notNullValue()); assertThat(request.getHeader(), notNullValue()); assertThat(request.getKey(), notNullValue()); assertThat(request.getExtras(), nullValue()); request.release(); MemcacheContent content1 = (MemcacheContent) channel.readInbound(); MemcacheContent content2 = (MemcacheContent) channel.readInbound(); assertThat(content1, instanceOf(MemcacheContent.class)); assertThat(content2, instanceOf(LastMemcacheContent.class)); assertThat(content1.content().readableBytes(), is(3)); assertThat(content2.content().readableBytes(), is(5)); content1.release(); content2.release(); }
public void consumePacket(ByteBuf data) { int cnt = data.readableBytes() / 4; dimensions = new int[cnt]; for (int i = 0; i < cnt; i++) { dimensions[i] = data.readInt(); } }
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(); } } } }
@Override public boolean renameTo(File dest) throws IOException { if (dest == null) { throw new NullPointerException("dest"); } if (byteBuf == null) { // empty file dest.createNewFile(); isRenamed = true; return true; } int length = byteBuf.readableBytes(); FileOutputStream outputStream = new FileOutputStream(dest); FileChannel fileChannel = outputStream.getChannel(); int written = 0; if (byteBuf.nioBufferCount() == 1) { ByteBuffer byteBuffer = byteBuf.nioBuffer(); while (written < length) { written += fileChannel.write(byteBuffer); } } else { ByteBuffer[] byteBuffers = byteBuf.nioBuffers(); while (written < length) { written += fileChannel.write(byteBuffers); } } fileChannel.force(false); fileChannel.close(); outputStream.close(); isRenamed = true; return written == length; }
@Override public void fatalError(String message, String stack) { if (log.isDebugEnabled()) { log.debug("Sending HTTP error due to script error {}", message); } StringBuilder msg = new StringBuilder(message); if (stack != null) { msg.append('\n'); msg.append(stack); } ByteBuf data = Unpooled.copiedBuffer(msg, Charsets.UTF8); response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR); response.headers().add("Content-Type", "text/plain"); response.headers().add("Content-Length", data.readableBytes()); calculateKeepAlive(true); channel.write(response); DefaultHttpContent chunk = new DefaultHttpContent(data); channel.write(chunk); sendLastChunk(); channel.flush(); if (!keepAlive) { shutDown(); } }
@Override public void addContent(ByteBuf buffer, boolean last) throws IOException { if (buffer != null) { long localsize = buffer.readableBytes(); if (definedSize > 0 && definedSize < size + localsize) { throw new IOException("Out of size: " + (size + localsize) + " > " + definedSize); } size += localsize; if (byteBuf == null) { byteBuf = buffer; } else if (byteBuf instanceof CompositeByteBuf) { CompositeByteBuf cbb = (CompositeByteBuf) byteBuf; cbb.addComponent(buffer); cbb.writerIndex(cbb.writerIndex() + buffer.readableBytes()); } else { CompositeByteBuf cbb = compositeBuffer(); cbb.addComponents(byteBuf, buffer); cbb.writerIndex(byteBuf.readableBytes() + buffer.readableBytes()); byteBuf = cbb; } } if (last) { completed = true; } else { if (buffer == null) { throw new NullPointerException("buffer"); } } }
@Test public void testGZIP() throws Exception { ByteBuf data = Unpooled.wrappedBuffer("test".getBytes()); EmbeddedByteChannel chEncoder = new EmbeddedByteChannel(new JZlibEncoder(ZlibWrapper.GZIP)); chEncoder.writeOutbound(data.copy()); assertTrue(chEncoder.finish()); byte[] deflatedData = chEncoder.readOutbound().array(); EmbeddedByteChannel chDecoderGZip = new EmbeddedByteChannel(new JZlibDecoder(ZlibWrapper.GZIP)); chDecoderGZip.writeInbound(Unpooled.wrappedBuffer(deflatedData)); assertTrue(chDecoderGZip.finish()); assertEquals(data, chDecoderGZip.readInbound()); EmbeddedByteChannel chDecoderZlibOrNone = new EmbeddedByteChannel(new JZlibDecoder(ZlibWrapper.ZLIB_OR_NONE)); chDecoderZlibOrNone.writeInbound(Unpooled.wrappedBuffer(deflatedData)); assertTrue(chDecoderZlibOrNone.finish()); assertEquals(data, chDecoderZlibOrNone.readInbound()); }
@Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf buffer) throws IOException { writeDimensionPosToBuffer(buffer, target); buffer.writeInt(type); buffer.writeDouble(duration); encodePrimitiveArrayInto(buffer, args); }
@Override public void toBytes(ByteBuf buf) { buf.writeInt(xCoord); buf.writeInt(yCoord); buf.writeInt(zCoord); ByteBufUtils.writeTag(buf, tag); }
private boolean add(ByteBuf var1) { if (this.count == Native.IOV_MAX) { return false; } else { int var2 = var1.readableBytes(); if (var2 == 0) { return true; } else { long var3 = var1.memoryAddress(); int var5 = var1.readerIndex(); long var6 = this.memoryAddress(this.count++); long var8 = var6 + (long) ADDRESS_SIZE; if (ADDRESS_SIZE == 8) { PlatformDependent.putLong(var6, var3 + (long) var5); PlatformDependent.putLong(var8, (long) var2); } else { assert ADDRESS_SIZE == 4; PlatformDependent.putInt(var6, (int) var3 + var5); PlatformDependent.putInt(var8, var2); } this.size += (long) var2; return true; } } }