/** * Returns a <a href="http://en.wikipedia.org/wiki/Hex_dump">hex dump</a> * of the specified buffer's readable bytes. */ public static String hexDump(ByteBuf buffer) { return hexDump(buffer, buffer.readerIndex(), buffer.readableBytes()); }
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception { final byte[] array; final int offset; final int length = msg.readableBytes(); if (msg.hasArray()) { array = msg.array(); offset = msg.arrayOffset() + msg.readerIndex(); } else { array = ByteBufUtil.getBytes(msg, msg.readerIndex(), length, false); offset = 0; } MessageNano prototype = clazz.getConstructor().newInstance(); out.add(MessageNano.mergeFrom(prototype, array, offset, length)); } }
static void writeString(ByteBuf buffer, String value) { final ByteBuf buf = buffer.alloc().buffer(ByteBufUtil.utf8MaxBytes(value)); try { final int length = ByteBufUtil.writeUtf8(buf, value); buffer.writeShort(length); buffer.writeBytes(buf); } finally { buf.release(); } }
/** * Encode a {@link CharSequence} in <a href="http://en.wikipedia.org/wiki/UTF-8">UTF-8</a> and write * it to a {@link ByteBuf} allocated with {@code alloc}. * @param alloc The allocator used to allocate a new {@link ByteBuf}. * @param seq The characters to write into a buffer. * @return The {@link ByteBuf} which contains the <a href="http://en.wikipedia.org/wiki/UTF-8">UTF-8</a> encoded * result. */ public static ByteBuf writeUtf8(ByteBufAllocator alloc, CharSequence seq) { // UTF-8 uses max. 3 bytes per char, so calculate the worst case. ByteBuf buf = alloc.buffer(utf8MaxBytes(seq)); writeUtf8(buf, seq); return buf; }
@Override public DataBuffer write(CharSequence charSequence, Charset charset) { Assert.notNull(charSequence, "CharSequence must not be null"); Assert.notNull(charset, "Charset must not be null"); if (StandardCharsets.UTF_8.equals(charset)) { ByteBufUtil.writeUtf8(this.byteBuf, charSequence); } else if (StandardCharsets.US_ASCII.equals(charset)) { ByteBufUtil.writeAscii(this.byteBuf, charSequence); } else { return PooledDataBuffer.super.write(charSequence, charset); } return this; }
/** * Read bytes from the given {@link ByteBuffer} into the given {@link OutputStream} using the {@code position} and * {@code length}. The position and limit of the given {@link ByteBuffer} may be adjusted. */ static void readBytes(ByteBufAllocator allocator, ByteBuffer buffer, int position, int length, OutputStream out) throws IOException { if (buffer.hasArray()) { out.write(buffer.array(), position + buffer.arrayOffset(), length); } else { int chunkLen = Math.min(length, WRITE_CHUNK_SIZE); buffer.clear().position(position); if (length <= MAX_TL_ARRAY_LEN || !allocator.isDirectBufferPooled()) { getBytes(buffer, threadLocalTempArray(chunkLen), 0, chunkLen, out, length); } else { // if direct buffers are pooled chances are good that heap buffers are pooled as well. ByteBuf tmpBuf = allocator.heapBuffer(chunkLen); try { byte[] tmp = tmpBuf.array(); int offset = tmpBuf.arrayOffset(); getBytes(buffer, tmp, offset, chunkLen, out, length); } finally { tmpBuf.release(); } } } }
@Override protected void encode(ChannelHandlerContext ctx, CharSequence msg, List<Object> out) throws Exception { ByteBuf buffer = ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(msg), charset, lineSeparator.length); buffer.writeBytes(lineSeparator); out.add(buffer); } }
final ByteBuf out = encoder.allocateBuffer(ctx.alloc()); encoder.encodePacket(packet, out, ctx.alloc(), true); log.trace("Out message: {} sessionId: {}", out.toString(CharsetUtil.UTF_8), msg.getSessionId()); if (out.isReadable()) { writeFutureList.add(ctx.channel().writeAndFlush(res)); } else { out.release(); outBuf.writeBytes(buf); if (log.isTraceEnabled()) { log.trace("Out attachment: {} sessionId: {}", ByteBufUtil.hexDump(outBuf), msg.getSessionId()); writeFutureList.add(ctx.channel().writeAndFlush(new BinaryWebSocketFrame(outBuf)));
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (!suppressRead && !handshakeFailed) { final int writerIndex = in.writerIndex(); try { loop: for (int i = 0; i < MAX_SSL_RECORDS; i++) { final int readerIndex = in.readerIndex(); final int readableBytes = writerIndex - readerIndex; if (readableBytes < SslUtils.SSL_RECORD_HEADER_LENGTH) { final int command = in.getUnsignedByte(readerIndex); handshakeFailed = true; NotSslRecordException e = new NotSslRecordException( "not an SSL/TLS record: " + ByteBufUtil.hexDump(in)); in.skipBytes(in.readableBytes()); ctx.fireUserEventTriggered(new SniCompletionEvent(e)); SslUtils.handleHandshakeFailure(ctx, e, true); throw e; logger.debug("Unexpected client hello packet: " + ByteBufUtil.hexDump(in), e);
/** * Decodes the settings header and returns a {@link Http2Settings} object. */ private Http2Settings decodeSettingsHeader(ChannelHandlerContext ctx, CharSequence settingsHeader) throws Http2Exception { ByteBuf header = ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(settingsHeader), CharsetUtil.UTF_8); try { // Decode the SETTINGS payload. ByteBuf payload = Base64.decode(header, URL_SAFE); // Create an HTTP/2 frame for the settings. ByteBuf frame = createSettingsFrame(ctx, payload); // Decode the SETTINGS frame and return the settings object. return decodeSettings(ctx, frame); } finally { header.release(); } }
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { int prefaceLength = CONNECTION_PREFACE.readableBytes(); int bytesRead = Math.min(in.readableBytes(), prefaceLength); if (!ByteBufUtil.equals(CONNECTION_PREFACE, CONNECTION_PREFACE.readerIndex(), in, in.readerIndex(), bytesRead)) { ctx.pipeline().remove(this); } else if (bytesRead == prefaceLength) { // Full h2 preface match, removed source codec, using http2 codec to handle // following network traffic ctx.pipeline() .remove(httpServerCodec) .remove(httpServerUpgradeHandler); ctx.pipeline().addAfter(ctx.name(), null, http2ServerHandler); ctx.pipeline().remove(this); ctx.fireUserEventTriggered(PriorKnowledgeUpgradeEvent.INSTANCE); } } }
/** * Returns {@code true} if and only if the two specified buffers are * identical to each other as described in {@link ByteBuf#equals(Object)}. * This method is useful when implementing a new buffer type. */ public static boolean equals(ByteBuf bufferA, ByteBuf bufferB) { final int aLen = bufferA.readableBytes(); if (aLen != bufferB.readableBytes()) { return false; } return equals(bufferA, bufferA.readerIndex(), bufferB, bufferB.readerIndex(), aLen); }
LOG.trace("0x{} buf {}", Long.toHexString(sessionId), ByteBufUtil.hexDump(buf)); queuedBuffer = channel.alloc().buffer(buf.readableBytes()); queuedBuffer.writeBytes(buf); if (LOG.isTraceEnabled()) { LOG.trace("0x{} queuedBuffer {}", Long.toHexString(sessionId), ByteBufUtil.hexDump(queuedBuffer)); queuedBuffer.writeBytes(buf); processQueuedBuffer(); } else { queuedBuffer = channel.alloc().buffer(buf.readableBytes()); queuedBuffer.writeBytes(buf); LOG.trace("0x{} queuedBuffer {}", Long.toHexString(sessionId), ByteBufUtil.hexDump(queuedBuffer));
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { logger.debug("channel read"); ByteBuf byteBuf = (ByteBuf)msg; if (logger.isTraceEnabled()) { logger.trace("\n{}", ByteBufUtil.prettyHexDump(byteBuf)); } OkPacket okPacket = new OkPacket(); okPacket.setAffectedRows(0); okPacket.setSequenceNumber(2); ByteBuf buffer = ctx.alloc().buffer(); try { transcoder.encode(okPacket, buffer); } catch (Exception e) { } logger.trace("\n{}", ByteBufUtil.prettyHexDump(buffer)); ctx.writeAndFlush(buffer); ((ByteBuf) msg).release(); }
@Override protected void messageReceived(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception { component.setCustomMDC(); try { Object o = Serializers.fromBinary(msg.content(), msg); if (o instanceof AckRequestMsg) { AckRequestMsg arm = (AckRequestMsg) o; ByteBuf buf = ctx.alloc().ioBuffer(NettyNetwork.INITIAL_BUFFER_SIZE, NettyNetwork.SEND_BUFFER_SIZE); component.deliverMessage(arm.content, ctx.channel()); component.extLog.trace("Got AckRequest for {}. Replying...", arm.id); NotifyAck ack = arm.reply(); Serializers.toBinary(ack, buf); DatagramPacket pack = new DatagramPacket(buf, ack.getDestination().asSocket()); component.extLog.trace("Sending Datagram ACK {} ({}bytes)", ack, buf.readableBytes()); ctx.writeAndFlush(pack); } else if (o instanceof Msg) { Msg m = (Msg) o; component.deliverMessage(m, ctx.channel()); } else { component.extLog.warn("Got unexpected Datagram message type: {} -> {}", o.getClass().getCanonicalName(), o); } } catch (Exception e) { // Catch anything...the Serializer could throw any kind of weird exception if you get message that were send by someone else component.extLog.warn("Got weird Datagram message, ignoring it: {}", ByteBufUtil.hexDump(msg.content())); component.extLog.trace("Exception was: \n{}", e); } finally { MDC.clear(); } }
@Override protected final void decode(final ChannelHandlerContext context, final ByteBuf in, final List<Object> out) { int readableBytes = in.readableBytes(); if (!isValidHeader(readableBytes)) { return; } if (log.isDebugEnabled()) { log.debug("Read from client {} : \n {}", context.channel().id().asShortText(), ByteBufUtil.prettyHexDump(in)); } doDecode(context, in, out, readableBytes); }
/** * Returns a multi-line hexadecimal dump of the specified {@link ByteBuf} that is easy to read by humans. */ public static String prettyHexDump(ByteBuf buffer) { return prettyHexDump(buffer, buffer.readerIndex(), buffer.readableBytes()); }
@SuppressWarnings("UnusedDeclaration") public void $(CharSequence charSequence) { //CHECKSTYLE:ON ByteBuf byteBuf = ByteBufUtil.encodeString(buffer.alloc(), CharBuffer.wrap(charSequence.toString()), CharsetUtil.UTF_8); buffer.writeBytes(byteBuf); byteBuf.release(); }
@Override protected void encode(ChannelHandlerContext ctx, CharSequence msg, List<Object> out) throws Exception { if (msg.length() == 0) { return; } out.add(ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(msg), charset)); } }
/** * Create a copy of the underlying storage from {@code buf} into a byte array. * The copy will start at {@link ByteBuf#readerIndex()} and copy {@link ByteBuf#readableBytes()} bytes. */ public static byte[] getBytes(ByteBuf buf) { return getBytes(buf, buf.readerIndex(), buf.readableBytes()); }