Example usage for io.netty.buffer ByteBufUtil prettyHexDump

List of usage examples for io.netty.buffer ByteBufUtil prettyHexDump

Introduction

In this page you can find the example usage for io.netty.buffer ByteBufUtil prettyHexDump.

Prototype

public static String prettyHexDump(ByteBuf buffer) 

Source Link

Document

Returns a multi-line hexadecimal dump of the specified ByteBuf that is easy to read by humans.

Usage

From source file:com.ibasco.agql.protocols.valve.source.query.handlers.SourceRconRequestEncoder.java

License:Open Source License

@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));
    }// w  w w .  j a v a 2  s  .  c o  m

    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);
    }
}

From source file:com.ibasco.agql.protocols.valve.source.query.SourceRconPacketBuilder.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*ww  w  .j a  v  a  2s  .c  o  m*/
public <T extends SourceRconPacket> T construct(ByteBuf data) {
    try {
        if (data.readableBytes() < 14) {
            log.warn("Packet is less than 10 bytes. Unsupported packet.");
            if (log.isDebugEnabled())
                log.debug("Unrecognized Packet: \n{}", ByteBufUtil.prettyHexDump(data));
            return null;
        }

        //Remember the reader index
        data.markReaderIndex();

        //Read from the listen
        data.readerIndex(0);
        int size = data.readIntLE();
        int id = data.readIntLE();
        int type = data.readIntLE();

        String body = data.readCharSequence(data.readableBytes() - 2, StandardCharsets.UTF_8).toString();

        SourceRconResponsePacket packet = getResponsePacket(type);

        if (packet != null) {
            //Ok, we have a valid response packet. Lets keep reading.
            packet.setId(id);
            packet.setSize(size);
            packet.setType(type);
            packet.setBody(body);
            return (T) packet;
        }
    } finally {
        //Reset the index
        data.resetReaderIndex();
    }
    return null;
}

From source file:netty.protocol.echo.EchoClientHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    LOG.info("Client received msg:" + ByteBufUtil.prettyHexDump((ByteBuf) msg));
    ctx.write(msg);
}

From source file:netty.protocol.echo.EchoServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    //log out the msg
    LOG.info("Server received msg:" + ByteBufUtil.prettyHexDump((ByteBuf) msg));

    ctx.write(msg);//  w  w  w  . jav  a  2s  .com
}

From source file:org.apache.bookkeeper.tools.cli.commands.bookie.ReadLedgerCommand.java

License:Apache License

private boolean readledger(ServerConfiguration serverConf, ReadLedgerFlags flags)
        throws InterruptedException, BKException, IOException {

    long lastEntry = flags.lastEntryId;

    final BookieSocketAddress bookie;
    if (flags.bookieAddresss != null) {
        // A particular bookie was specified
        bookie = new BookieSocketAddress(flags.bookieAddresss);
    } else {/*from ww w .  j  av  a 2s .c o m*/
        bookie = null;
    }

    ClientConfiguration conf = new ClientConfiguration();
    conf.addConfiguration(serverConf);

    try (BookKeeperAdmin bk = new BookKeeperAdmin(conf)) {
        if (flags.forceRecovery) {
            // Force the opening of the ledger to trigger recovery
            try (LedgerHandle lh = bk.openLedger(flags.ledgerId)) {
                if (lastEntry == -1 || lastEntry > lh.getLastAddConfirmed()) {
                    lastEntry = lh.getLastAddConfirmed();
                }
            }
        }

        if (bookie == null) {
            // No bookie was specified, use normal bk client
            Iterator<LedgerEntry> entries = bk.readEntries(flags.ledgerId, flags.firstEntryId, lastEntry)
                    .iterator();
            while (entries.hasNext()) {
                LedgerEntry entry = entries.next();
                formatEntry(entry, flags.msg);
            }
        } else {
            // Use BookieClient to target a specific bookie
            EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
            OrderedExecutor executor = OrderedExecutor.newBuilder().numThreads(1).name("BookieClientScheduler")
                    .build();

            ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(
                    new DefaultThreadFactory("BookKeeperClientSchedulerPool"));

            BookieClient bookieClient = new BookieClientImpl(conf, eventLoopGroup,
                    UnpooledByteBufAllocator.DEFAULT, executor, scheduler, NullStatsLogger.INSTANCE);

            LongStream.range(flags.firstEntryId, lastEntry).forEach(entryId -> {
                CompletableFuture<Void> future = new CompletableFuture<>();

                bookieClient.readEntry(bookie, flags.ledgerId, entryId,
                        (rc, ledgerId1, entryId1, buffer, ctx) -> {
                            if (rc != BKException.Code.OK) {
                                LOG.error("Failed to read entry {} -- {}", entryId1,
                                        BKException.getMessage(rc));
                                future.completeExceptionally(BKException.create(rc));
                                return;
                            }

                            System.out
                                    .println("--------- Lid=" + ledgerIdFormatter.formatLedgerId(flags.ledgerId)
                                            + ", Eid=" + entryId + " ---------");
                            if (flags.msg) {
                                System.out.println("Data: " + ByteBufUtil.prettyHexDump(buffer));
                            }

                            future.complete(null);
                        }, null, BookieProtocol.FLAG_NONE);

                try {
                    future.get();
                } catch (Exception e) {
                    LOG.error("Error future.get while reading entries from ledger {}", flags.ledgerId, e);
                }
            });

            eventLoopGroup.shutdownGracefully();
            executor.shutdown();
            bookieClient.close();
        }
    }
    return true;
}

From source file:org.code_house.ebus.netty.codec.SlaveTelegramDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (in.readableBytes() == 0) {
        return;/*from   ww w.j  av  a2s  .co  m*/
    }

    int index = in.readerIndex();
    // no master, no slave, no broadcast -> slave reply or ACK
    if (in.readableBytes() >= 3) {
        // we have at least three bytes which should be slave ACK, slave reply len, slave crc.
        byte ack = in.readByte();
        if (ack == Constants.ACK) { // slave confirmed received data
            byte length = in.readByte();
            if (in.readableBytes() >= length + 1 /* crc */) {
                ByteBuffer exchange = ByteBuffer.allocate(length);
                in.getBytes(in.readerIndex(), exchange);
                in.skipBytes(length);
                byte crc = in.readByte();
                SlaveData data = new SlaveData(exchange, calculateCrc(length), crc);
                if (data.isValid()) {
                    // proper slave reply
                    out.add(new Confirmation());
                    out.add(new SlaveHeader(length));
                    out.add(data);
                } else {
                    System.out.println("Slave CRC fail!!!");
                    in.discardReadBytes();
                }
            }
        } else if (ack == Constants.NACK) {
            out.add(new Rejection());
        }
    }

    if (out.isEmpty()) {
        System.out.println("slave fail -> \n" + ByteBufUtil.prettyHexDump(in));
        in.readerIndex(index);
    }

    if (in.readableBytes() > 0) {
        out.add(in.readBytes(super.actualReadableBytes()));
    }
}

From source file:org.jocean.aliyun.oss.internal.OSSRequestSigner.java

License:Apache License

public void sign(final HttpRequest request) throws ClientException {
    String accessKeyId = creds.getAccessKeyId();
    String secretAccessKey = creds.getSecretAccessKey();

    if (accessKeyId.length() > 0 && secretAccessKey.length() > 0) {
        final String canonicalString = SignUtils.buildCanonicalString(request.method().toString(), resourcePath,
                request, null);// w w  w  .jav a2  s. co m

        if (LOG.isDebugEnabled()) {
            LOG.debug("sign: canonicalString is {} AS HEX\n{}", canonicalString, ByteBufUtil
                    .prettyHexDump(Unpooled.wrappedBuffer(canonicalString.getBytes(CharsetUtil.UTF_8))));
        }

        final String signature = ServiceSignature.create().computeSignature(secretAccessKey, canonicalString);

        if (LOG.isDebugEnabled()) {
            LOG.debug("sign: getAccessKeyId {} and signature {}", accessKeyId, signature);
        }

        request.headers().add(OSSHeaders.AUTHORIZATION,
                OSSUtils.composeRequestAuthorization(accessKeyId, signature));
    }
}

From source file:org.opendaylight.lispflowmapping.southbound.lisp.LispSouthboundHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
    if (LOG.isTraceEnabled()) {
        LOG.trace("Received UDP packet from {}:{} with content:\n{}", msg.sender().getHostString(),
                msg.sender().getPort(), ByteBufUtil.prettyHexDump(msg.content()));
    }//from   w  ww  .j a  v a2  s  . co m
    handlePacket(msg);
}

From source file:org.opendaylight.lispflowmapping.southbound.LispSouthboundPlugin.java

License:Open Source License

public void handleSerializedLispBuffer(TransportAddress address, ByteBuffer outBuffer,
        final MessageType packetType) {
    InetAddress ip = InetAddresses.forString(new String(address.getIpAddress().getValue()));
    InetSocketAddress recipient = new InetSocketAddress(ip, address.getPort().getValue());
    // the wrappedBuffer() method doesn't copy data, so this conversion shouldn't hurt performance
    ByteBuf data = wrappedBuffer(outBuffer.array());
    DatagramPacket packet = new DatagramPacket(data, recipient);
    LOG.debug("Sending {} on port {} to address: {}", packetType, address.getPort().getValue(), ip);
    if (LOG.isTraceEnabled()) {
        LOG.trace("Buffer:\n{}", ByteBufUtil.prettyHexDump(data));
    }//from w w w  . j  a  v  a2 s  . c  om
    channel.write(packet).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                LOG.trace("Success");
                statistics.incrementTx(packetType.getIntValue());
            } else {
                LOG.warn("Failed to send packet");
                statistics.incrementTxErrors();
            }
        }
    });
    channel.flush();
}

From source file:pl.tcs.btppllib.DeviceGetTimeTest.java

protected static ByteBuf buildGetTimeRequest() {
    log.debug("*** Build GetTime request");

    ByteBuf retBuf = Unpooled.buffer(256);

    // preamble:/*from  w ww. jav  a2 s .  com*/
    retBuf.writeByte(0);
    retBuf.writeByte(0);
    retBuf.writeByte(0);
    retBuf.writeByte(0x12);

    // rest:

    retBuf.writeByte(toUnsigned(TG_HEADER_SZ));
    retBuf.writeByte(toUnsigned(BtpplChecksumType.BtpplFletcherOnly.getVal()));
    final long utcTime = getUTCTime();

    //        retBuf.writeShort((int)utcTime);
    retBuf.writeShort(0x4397);
    retBuf.writeShort(subsecondDiscriminator);
    //        subsecondDiscriminator++;

    retBuf.writeShort(0); // member
    retBuf.writeShort(815); // otype        
    retBuf.writeShort(103); // method (103 = GetTime)

    retBuf.writeShort(1);
    retBuf.writeShort(100);

    //        int writerIdx = retBuf.writerIndex();
    //        log.debug("@Writer index: " + writerIdx);
    int nb = retBuf.readableBytes() - 4;
    byte[] fletcherInput = new byte[nb];
    retBuf.getBytes(4, fletcherInput);
    //        for (int i = 0; i < fletcherInput.length; i++) {
    //            fletcherInput[i] = (byte)(fletcherInput[i] & 0xFF);            
    //        }        
    log.info("BUF: " + getBufStr(fletcherInput));
    FletcherChecksum fcs = new FletcherChecksum(fletcherInput);
    //        byte[] checksum = fcs.getChecksum(); 
    //        retBuf.writeByte(toUnsigned(checksum[0]));
    //        retBuf.writeByte(toUnsigned(checksum[1]));
    int checksumInt = fcs.getChecksumAsInt();

    log.info(String.format("********** 0x%x VS 0x%x", checksumInt, 0xe530));
    retBuf.writeShort(checksumInt);
    //        retBuf.writeShort(0xe530);

    log.debug("LogBuf: " + ByteBufUtil.prettyHexDump(retBuf));

    return retBuf;
}