Example usage for io.netty.buffer ByteBufUtil hexDump

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

Introduction

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

Prototype

public static String hexDump(byte[] array) 

Source Link

Document

Returns a <a href="http://en.wikipedia.org/wiki/Hex_dump">hex dump</a> of the specified byte array.

Usage

From source file:me.nithanim.cultures.format.cif.CifFileWriter.java

@Override
public void pack(CifFile o, ByteBuf buf) throws IOException {
    List<String> lines = o.getLines();

    ByteBufAllocator alloc = ByteBufAllocator.DEFAULT;
    ByteBuf indexTable = alloc.buffer(o.getLines().size()).order(ByteOrder.LITTLE_ENDIAN);
    ByteBuf contentTable = alloc.buffer(o.getLines().size() * 10).order(ByteOrder.LITTLE_ENDIAN);
    if (o.getFileFormat() == CifFile.FileFormat.CIF) {
        for (String l : lines) {
            int idx = contentTable.writerIndex();
            ByteBufUtil.hexDump(contentTable);
            indexTable.writeInt(idx);/*from   w w  w . j a v a  2s  .  c  o m*/

            l = l.trim();
            if (l.startsWith("[")) {
                l = l.substring(1, l.length() - 1);
                contentTable.writeByte(1);
            } else {
                contentTable.writeByte(2);
            }

            contentTable.writeBytes(l.getBytes(CharsetUtil.ISO_8859_1));
            contentTable.writeByte('\0');
        }
    } else {
        for (String l : lines) {
            int idx = contentTable.writerIndex();
            indexTable.writeInt(idx);

            l = l.trim();

            contentTable.writeBytes(l.getBytes(CharsetUtil.ISO_8859_1));
            contentTable.writeByte('\0');
        }
    }
    EncryptedInformation ei = new EncryptedInformation(o.getLines().size(), indexTable.writerIndex(),
            indexTable, contentTable.writerIndex(), contentTable);

    Writer<EncryptedInformation> eiw;
    if (o.getInternalFormat() == CifFile.InternalFormat.TYPE1) {
        buf.writeInt(65601);
        eiw = type1Writer;
    } else if (o.getInternalFormat() == CifFile.InternalFormat.TYPE2) {
        buf.writeInt(1021);
        eiw = type2Writer;
    } else {
        throw new UnsupportedDataTypeException("The given data is not a cif file!");
    }
    eiw.pack(ei, buf);
}

From source file:nearenough.protocol.RtMessage.java

License:Open Source License

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');
            }// w  ww.  j a v a 2 s. c  o  m
        });
    }
    sb.append(indent1).append("}\n");
    return sb.toString();
}

From source file:nenea.client.file.FileClientHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    System.out.println("channelRead0");
    ByteBuf buf = (ByteBuf) msg;// w  w  w  .  j a va  2 s .  c  o m
    System.out.println(buf.readableBytes());
    System.out.println(msg);
    System.out.println(buf.toString(CharsetUtil.UTF_8));
    System.out.println((ByteBufUtil.hexDump(buf)));

    // byte[] msgg = buf.array();
    // System.out.println(buf.readInt());

    int header1 = buf.readInt();
    String header2 = buf.readBytes(header1).toString(CharsetUtil.UTF_8);
    long header3 = buf.readLong();

    System.err.println(header1);
    System.err.println(header2);
    System.err.println(header3);

}

From source file:nenea.client.operation.OperationClientHandler.java

License:Apache License

private ByteBuf initializeProtocol(String msg, Channel ch) throws UnsupportedEncodingException {
    System.out.println("make JOIN Header");
    ByteBuf buf = ch.alloc().heapBuffer(OP_CODE_JOIN.length() + 12 + msg.getBytes("UTF-8").length);

    buf.writeInt(OP_CODE_JOIN.length());
    buf.writeBytes(OP_CODE_JOIN.getBytes());
    buf.writeLong(msg.getBytes("UTF-8").length);
    buf.writeBytes(msg.getBytes("UTF-8"));

    System.out.println("buffer index : " + buf.writerIndex());
    System.out.println("hex : " + ByteBufUtil.hexDump(buf));

    return buf;/*from   w w  w  .j  av a2s. c om*/
}

From source file:org.apache.bookkeeper.bookie.storage.ldb.DbLedgerStorageTest.java

License:Apache License

@Test
public void testBookieCompaction() throws Exception {
    storage.setMasterKey(4, "key".getBytes());

    ByteBuf entry3 = Unpooled.buffer(1024);
    entry3.writeLong(4); // ledger id
    entry3.writeLong(3); // entry id
    entry3.writeBytes("entry-3".getBytes());
    storage.addEntry(entry3);/*w  w  w  .j ava 2  s . c om*/

    // Simulate bookie compaction
    SingleDirectoryDbLedgerStorage singleDirStorage = ((DbLedgerStorage) storage).getLedgerStorageList().get(0);
    EntryLogger entryLogger = singleDirStorage.getEntryLogger();
    // Rewrite entry-3
    ByteBuf newEntry3 = Unpooled.buffer(1024);
    newEntry3.writeLong(4); // ledger id
    newEntry3.writeLong(3); // entry id
    newEntry3.writeBytes("new-entry-3".getBytes());
    long location = entryLogger.addEntry(4L, newEntry3, false);

    List<EntryLocation> locations = Lists.newArrayList(new EntryLocation(4, 3, location));
    singleDirStorage.updateEntriesLocations(locations);

    ByteBuf res = storage.getEntry(4, 3);
    System.out.println("res:       " + ByteBufUtil.hexDump(res));
    System.out.println("newEntry3: " + ByteBufUtil.hexDump(newEntry3));
    assertEquals(newEntry3, res);
}

From source file:org.apache.directory.server.dhcp.netty.Dhcp6Handler.java

@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Incomming DHCP : {}, from: {}", ByteBufUtil.hexDump(msg.content()), msg.sender());
    }/*from   w  ww  . j  a  v a 2  s .  c  o m*/

    final Dhcp6Message incommingMsg;
    try {
        incommingMsg = dhcp6MessageDecoder.decode(msg.content().nioBuffer());
    } catch (final Dhcp6Exception.UnknownMsgException e) {
        LOG.warn("Unknown DHCP message type: {}. Ignoring", ByteBufUtil.hexDump(msg.content()), e);
        return;
    }

    final Optional<Dhcp6Message> reply = dhcpService
            .getReplyFor(new Dhcp6RequestContext(msg.sender().getAddress()), incommingMsg);

    if (reply.isPresent()) {
        LOG.debug("Responding with message: {}", reply.get());

        // TODO what size to allocate the buffer to ?
        ByteBuf buf = ctx.alloc().buffer(1024);
        ByteBuffer buffer = buf.nioBuffer(buf.writerIndex(), buf.writableBytes());
        dhcp6MessageEncoder.encode(buffer, reply.get());
        buffer.flip();
        buf.writerIndex(buf.writerIndex() + buffer.remaining());
        DatagramPacket packet = new DatagramPacket(buf, msg.sender());
        ctx.write(packet);
    } else {
        LOG.warn("No response from DHCP service received for: {}. Ignoring.", incommingMsg);
    }
}

From source file:org.apache.qpid.jms.provider.amqp.AmqpProvider.java

License:Apache License

@Override
public void onData(final ByteBuf input) {

    // We need to retain until the serializer gets around to processing it.
    ReferenceCountUtil.retain(input);//  ww  w  . ja  va2 s.  c  om

    serializer.execute(new Runnable() {

        @Override
        public void run() {
            try {
                if (isTraceBytes()) {
                    TRACE_BYTES.info("Received: {}", ByteBufUtil.hexDump(input));
                }

                ByteBuffer source = input.nioBuffer();

                do {
                    ByteBuffer buffer = protonTransport.getInputBuffer();
                    int limit = Math.min(buffer.remaining(), source.remaining());
                    ByteBuffer duplicate = source.duplicate();
                    duplicate.limit(source.position() + limit);
                    buffer.put(duplicate);
                    protonTransport.processInput().checkIsOk();
                    source.position(source.position() + limit);
                } while (source.hasRemaining());

                ReferenceCountUtil.release(input);

                // Process the state changes from the latest data and then answer back
                // any pending updates to the Broker.
                processUpdates();
                pumpToProtonTransport();
            } catch (Throwable t) {
                LOG.warn("Caught problem during data processing: {}", t.getMessage(), t);

                fireProviderException(t);
            }
        }
    });
}

From source file:org.apache.qpid.jms.provider.amqp.AmqpProvider.java

License:Apache License

protected boolean pumpToProtonTransport(AsyncResult request) {
    try {/*from  w w w. j  a  v a 2 s. co m*/
        boolean done = false;
        while (!done) {
            ByteBuffer toWrite = protonTransport.getOutputBuffer();
            if (toWrite != null && toWrite.hasRemaining()) {
                ByteBuf outbound = transport.allocateSendBuffer(toWrite.remaining());
                outbound.writeBytes(toWrite);

                if (isTraceBytes()) {
                    TRACE_BYTES.info("Sending: {}", ByteBufUtil.hexDump(outbound));
                }

                transport.send(outbound);
                protonTransport.outputConsumed();
            } else {
                done = true;
            }
        }
    } catch (IOException e) {
        fireProviderException(e);
        request.onFailure(e);
        return false;
    }

    return true;
}

From source file:org.apache.zookeeper.server.NettyServerCnxn.java

License:Apache License

/**
 * Process incoming message. This should only be called from the event
 * loop thread.//from  w w w .ja  va 2  s.  co m
 * @param buf the message bytes to process.
 */
void processMessage(ByteBuf buf) {
    assert channel.eventLoop().inEventLoop();
    if (LOG.isDebugEnabled()) {
        LOG.debug("0x{} queuedBuffer: {}", Long.toHexString(sessionId), queuedBuffer);
    }

    if (LOG.isTraceEnabled()) {
        LOG.trace("0x{} buf {}", Long.toHexString(sessionId), ByteBufUtil.hexDump(buf));
    }

    if (throttled.get()) {
        LOG.debug("Received message while throttled");
        // we are throttled, so we need to queue
        if (queuedBuffer == null) {
            LOG.debug("allocating queue");
            queuedBuffer = channel.alloc().buffer(buf.readableBytes());
        }
        queuedBuffer.writeBytes(buf);
        if (LOG.isTraceEnabled()) {
            LOG.trace("0x{} queuedBuffer {}", Long.toHexString(sessionId), ByteBufUtil.hexDump(queuedBuffer));
        }
    } else {
        LOG.debug("not throttled");
        if (queuedBuffer != null) {
            queuedBuffer.writeBytes(buf);
            processQueuedBuffer();
        } else {
            receiveMessage(buf);
            // Have to check !closingChannel, because an error in
            // receiveMessage() could have led to close() being called.
            if (!closingChannel && buf.isReadable()) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Before copy {}", buf);
                }
                if (queuedBuffer == null) {
                    queuedBuffer = channel.alloc().buffer(buf.readableBytes());
                }
                queuedBuffer.writeBytes(buf);
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Copy is {}", queuedBuffer);
                    LOG.trace("0x{} queuedBuffer {}", Long.toHexString(sessionId),
                            ByteBufUtil.hexDump(queuedBuffer));
                }
            }
        }
    }
}

From source file:org.apache.zookeeper.server.NettyServerCnxn.java

License:Apache License

/**
 * Try to process previously queued message. This should only be called
 * from the event loop thread./*w  w  w.  j  av a  2  s  .  co m*/
 */
void processQueuedBuffer() {
    assert channel.eventLoop().inEventLoop();
    if (queuedBuffer != null) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("processing queue 0x{} queuedBuffer {}", Long.toHexString(sessionId),
                    ByteBufUtil.hexDump(queuedBuffer));
        }
        receiveMessage(queuedBuffer);
        if (closingChannel) {
            // close() could have been called if receiveMessage() failed
            LOG.debug("Processed queue - channel closed, dropping remaining bytes");
        } else if (!queuedBuffer.isReadable()) {
            LOG.debug("Processed queue - no bytes remaining");
            releaseQueuedBuffer();
        } else {
            LOG.debug("Processed queue - bytes remaining");
        }
    } else {
        LOG.debug("queue empty");
    }
}