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:cc.io.lessons.server.HttpUploadServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

    if (msg instanceof HttpRequest) {
        System.out.println(msg.toString());
    } else {//from www  .  ja v a  2  s  .  c o  m
        System.out.println(ByteBufUtil.hexDump(((HttpContent) msg).content()));
        //System.out.println(((HttpContent) msg).content().toString(Charset.defaultCharset()));
    }

    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        URI uri = new URI(request.getUri());
        if (!uri.getPath().startsWith("/form")) {
            // Write Menu
            writeMenu(ctx);
            return;
        }
        responseContent.setLength(0);
        responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        responseContent.append("===================================\r\n");

        responseContent.append("VERSION: " + request.getProtocolVersion().text() + "\r\n");

        responseContent.append("REQUEST_URI: " + request.getUri() + "\r\n\r\n");
        responseContent.append("\r\n\r\n");

        // new getMethod
        List<Entry<String, String>> headers = request.headers().entries();
        for (Entry<String, String> entry : headers) {
            responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        // new getMethod
        Set<Cookie> cookies;
        String value = request.headers().get(COOKIE);
        if (value == null) {
            cookies = Collections.emptySet();
        } else {
            cookies = CookieDecoder.decode(value);
        }
        for (Cookie cookie : cookies) {
            responseContent.append("COOKIE: " + cookie.toString() + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        QueryStringDecoder decoderQuery = new QueryStringDecoder(request.getUri());
        Map<String, List<String>> uriAttributes = decoderQuery.parameters();
        for (Entry<String, List<String>> attr : uriAttributes.entrySet()) {
            for (String attrVal : attr.getValue()) {
                responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n");
            }
        }
        responseContent.append("\r\n\r\n");

        // if GET Method: should not try to create a HttpPostRequestDecoder
        try {
            decoder = new HttpPostRequestDecoder(factory, request);
        } catch (ErrorDataDecoderException e1) {
            e1.printStackTrace();
            responseContent.append(e1.getMessage());
            writeResponse(ctx.channel());
            ctx.channel().close();
            return;
        } catch (IncompatibleDataDecoderException e1) {
            // GET Method: should not try to create a HttpPostRequestDecoder
            // So OK but stop here
            responseContent.append(e1.getMessage());
            responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n");
            writeResponse(ctx.channel());
            return;
        }

        readingChunks = HttpHeaders.isTransferEncodingChunked(request);
        responseContent.append("Is Chunked: " + readingChunks + "\r\n");
        responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n");
        if (readingChunks) {
            // Chunk version
            responseContent.append("Chunks: ");
            readingChunks = true;
        }
    }

    // check if the decoder was constructed before
    // if not it handles the form get
    if (decoder != null) {
        if (msg instanceof HttpContent) {
            // New chunk is received
            HttpContent chunk = (HttpContent) msg;
            try {
                decoder.offer(chunk);
            } catch (ErrorDataDecoderException e1) {
                e1.printStackTrace();
                responseContent.append(e1.getMessage());
                writeResponse(ctx.channel());
                ctx.channel().close();
                return;
            }
            responseContent.append('o');
            // example of reading chunk by chunk (minimize memory usage due to
            // Factory)
            readHttpDataChunkByChunk();
            // example of reading only if at the end
            if (chunk instanceof LastHttpContent) {
                writeResponse(ctx.channel());
                readingChunks = false;

                reset();
            }
        }
    }
}

From source file:com.chiorichan.http.ssl.SniNegotiator.java

License:Mozilla Public License

private String sniHostNameFromHandshakeInfo(ByteBuf in) {
    int readerIndex = in.readerIndex();
    try {/* www.  j  a v  a2 s.c om*/
        int command = in.getUnsignedByte(readerIndex);

        // tls, but not handshake command
        switch (command) {
        case SslConstants.SSL_CONTENT_TYPE_CHANGE_CIPHER_SPEC:
        case SslConstants.SSL_CONTENT_TYPE_ALERT:
        case SslConstants.SSL_CONTENT_TYPE_APPLICATION_DATA:
            return null;
        case SslConstants.SSL_CONTENT_TYPE_HANDSHAKE:
            break;
        default:
            //not tls or sslv3, do not try sni
            handshaken = true;
            return null;
        }

        int majorVersion = in.getUnsignedByte(readerIndex + 1);

        // SSLv3 or TLS
        if (majorVersion == 3) {
            int packetLength = in.getUnsignedShort(readerIndex + 3) + 5;

            if (in.readableBytes() >= packetLength) {
                // decode the ssl client hello packet
                // we have to skip some var-length fields
                int offset = readerIndex + 43;

                int sessionIdLength = in.getUnsignedByte(offset);
                offset += sessionIdLength + 1;

                int cipherSuitesLength = in.getUnsignedShort(offset);
                offset += cipherSuitesLength + 2;

                int compressionMethodLength = in.getUnsignedByte(offset);
                offset += compressionMethodLength + 1;

                int extensionsLength = in.getUnsignedShort(offset);
                offset += 2;
                int extensionsLimit = offset + extensionsLength;

                while (offset < extensionsLimit) {
                    int extensionType = in.getUnsignedShort(offset);
                    offset += 2;

                    int extensionLength = in.getUnsignedShort(offset);
                    offset += 2;

                    // SNI
                    if (extensionType == 0) {
                        handshaken = true;
                        int serverNameType = in.getUnsignedByte(offset + 2);
                        if (serverNameType == 0) {
                            int serverNameLength = in.getUnsignedShort(offset + 3);
                            return in.toString(offset + 5, serverNameLength, CharsetUtil.UTF_8);
                        } else
                            // invalid enum value
                            return null;
                    }

                    offset += extensionLength;
                }

                handshaken = true;
                return null;
            } else
                // client hello incomplete
                return null;
        } else {
            handshaken = true;
            return null;
        }
    } catch (Throwable e) {
        // unexpected encoding, ignore sni and use default
        if (logger.isDebugEnabled())
            logger.debug("Unexpected client hello packet: " + ByteBufUtil.hexDump(in), e);
        handshaken = true;
        return null;
    }
}

From source file:com.cloudhopper.smpp.channel.SmppSessionLogger.java

License:Apache License

/**
 * Logs the specified event to the {@link InternalLogger} returned by
 * {@link #getLogger()}. If hex dump has been enabled for this handler,
 * the hex dump of the {@link ByteBuf} in a {@link Object} will
 * be logged together./*from w  ww  . j av a2s  .  c  o m*/
 */
protected void log(Direction direction, Object obj) {
    // handle logging of message events (PDU, ByteBuf, etc.)
    if ((obj instanceof ByteBuf) && this.options.isLogBytesEnabled()) {
        ByteBuf buffer = (ByteBuf) obj;
        if (direction == Direction.UP) {
            logger.info("read bytes: [{}]", ByteBufUtil.hexDump(buffer));
        } else if (direction == Direction.DOWN) {
            logger.info("write bytes: [{}]", ByteBufUtil.hexDump(buffer));
        }
    }
}

From source file:com.cloudhopper.smpp.simulator.SmppSimulatorSessionHandler.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
    // ignore requests with zero bytes
    if (buffer.readableBytes() <= 0) {
        return;//from   ww w . jav a  2 s.  c o  m
    }

    // decode the buffer into a pdu
    Pdu pdu = transcoder.decode(buffer);

    // if the pdu was null, we don't have enough data yet
    if (pdu == null) {
        logger.info("Received data on channel {}, but not enough to parse PDU fully yet", channel.toString());
        logger.info("Bytes in buffer: [{}]", ByteBufUtil.hexDump(buffer));
        return;
    }

    logger.info("Decoded buffer on channel {} into PDU: {}", channel.toString(), pdu);

    // if we have a pdu procesor registered, let's see if it handles it
    boolean processed = false;
    if (this.pduProcessor != null) {
        processed = this.pduProcessor.process(this, channel, pdu);
    }

    if (processed) {
        logger.info("This PDU was processed by the registered PduProcessor");
    } else {
        this.pduQueue.add(pdu);
    }

    // is there a PDU someone wants us to write in response?
    if (this.writePduQueue.size() > 0) {
        Pdu pduToWrite = this.writePduQueue.remove();
        logger.info("Automatically writing back on channel {} the PDU: {}", channel.toString(), pduToWrite);
        ByteBuf writeBuffer = this.transcoder.encode(pduToWrite);
        channel.writeAndFlush(writeBuffer);
    }

    out.add(pdu);
}

From source file:com.corundumstudio.socketio.handler.EncoderHandler.java

License:Apache License

private void handleWebsocket(final OutPacketMessage msg, ChannelHandlerContext ctx) throws IOException {
    while (true) {
        Queue<Packet> queue = msg.getClientHead().getPacketsQueue(msg.getTransport());
        Packet packet = queue.poll();/*  ww w.  j  av  a 2 s.  c  o  m*/
        if (packet == null) {
            break;
        }

        final ByteBuf out = encoder.allocateBuffer(ctx.alloc());
        encoder.encodePacket(packet, out, ctx.alloc(), true);

        WebSocketFrame res = new TextWebSocketFrame(out);
        if (log.isTraceEnabled()) {
            log.trace("Out message: {} sessionId: {}", out.toString(CharsetUtil.UTF_8), msg.getSessionId());
        }
        if (out.isReadable()) {
            ctx.channel().writeAndFlush(res);
        } else {
            out.release();
        }

        for (ByteBuf buf : packet.getAttachments()) {
            ByteBuf outBuf = encoder.allocateBuffer(ctx.alloc());
            outBuf.writeByte(4);
            outBuf.writeBytes(buf);
            if (log.isTraceEnabled()) {
                log.trace("Out attachment: {} sessionId: {}", ByteBufUtil.hexDump(outBuf), msg.getSessionId());
            }
            ctx.channel().writeAndFlush(new BinaryWebSocketFrame(outBuf));
        }
    }
}

From source file:com.digitalpetri.opcua.stack.core.application.DefaultCertificateValidator.java

License:Apache License

private void certificateRejected(X509Certificate certificate) {
    try {/* w  ww.  ja v  a  2 s  .c om*/
        String[] ss = certificate.getSubjectX500Principal().getName().split(",");
        String name = ss.length > 0 ? ss[0] : certificate.getSubjectX500Principal().getName();
        String thumbprint = ByteBufUtil
                .hexDump(Unpooled.wrappedBuffer(DigestUtil.sha1(certificate.getEncoded())));

        String filename = String.format("%s [%s].der", URLEncoder.encode(name, "UTF-8"), thumbprint);

        File f = new File(rejectedDir.getAbsolutePath() + File.separator + filename);

        FileOutputStream fos = new FileOutputStream(f);
        fos.write(certificate.getEncoded());
        fos.flush();
        fos.close();

        logger.debug("Added rejected certificate entry: {}", filename);
    } catch (CertificateEncodingException | IOException e) {
        logger.error("Error adding rejected certificate entry.", e);
    }
}

From source file:com.fjn.helper.frameworkex.netty.v4.echotest.EchoClientHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
    System.out.println("Client received : " + ByteBufUtil.hexDump(msg.readBytes(msg.readableBytes())));
    msg.release();/*  ww  w .j  a va  2s . c om*/
}

From source file:com.growcontrol.common.netty.JsonObjectDecoder.java

License:Apache License

@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out)
        throws Exception {
    if (this.state == ST_CORRUPTED) {
        in.skipBytes(in.readableBytes());
        return;//www . j  a v a 2 s .  co m
    }
    // index of next byte to process.
    int idx = this.idx;
    final int wrtIdx = in.writerIndex();
    if (wrtIdx > this.maxObjectLength) {
        // buffer size exceeded maxObjectLength; discarding the complete buffer.
        in.skipBytes(in.readableBytes());
        reset();
        throw new TooLongFrameException(
                "object length exceeds " + this.maxObjectLength + ": " + wrtIdx + " bytes discarded");
    }
    for (/* use current idx */; idx < wrtIdx; idx++) {
        final byte c = in.getByte(idx);
        if (this.state == ST_DECODING_NORMAL) {
            decodeByte(c, in, idx);
            // All opening braces/brackets have been closed. That's enough to conclude
            // that the JSON object/array is complete.
            if (this.openBraces == 0) {
                ByteBuf json = extractObject(ctx, in, in.readerIndex(), idx + 1 - in.readerIndex());
                if (json != null) {
                    out.add(json);
                }
                // The JSON object/array was extracted => discard the bytes from
                // the input buffer.
                in.readerIndex(idx + 1);
                // Reset the object state to get ready for the next JSON object/text
                // coming along the byte stream.
                reset();
            }
        } else if (this.state == ST_DECODING_ARRAY_STREAM) {
            decodeByte(c, in, idx);
            if (!this.insideString && (this.openBraces == 1 && c == ',' || this.openBraces == 0 && c == ']')) {
                // skip leading spaces. No range check is needed and the loop will terminate
                // because the byte at position idx is not a whitespace.
                for (int i = in.readerIndex(); Character.isWhitespace(in.getByte(i)); i++) {
                    in.skipBytes(1);
                }
                // skip trailing spaces.
                int idxNoSpaces = idx - 1;
                while (idxNoSpaces >= in.readerIndex() && Character.isWhitespace(in.getByte(idxNoSpaces))) {
                    idxNoSpaces--;
                }
                ByteBuf json = extractObject(ctx, in, in.readerIndex(), idxNoSpaces + 1 - in.readerIndex());
                if (json != null) {
                    out.add(json);
                }
                in.readerIndex(idx + 1);
                if (c == ']') {
                    reset();
                }
            }
            // JSON object/array detected. Accumulate bytes until all braces/brackets are closed.
        } else if (c == '{' || c == '[') {
            initDecoding(c);
            // Discard the array bracket
            if (this.state == ST_DECODING_ARRAY_STREAM)
                in.skipBytes(1);
            // Discard leading spaces in front of a JSON object/array.
        } else if (Character.isWhitespace(c)) {
            in.skipBytes(1);
        } else {
            this.state = ST_CORRUPTED;
            throw new CorruptedFrameException(
                    "invalid JSON received at byte position " + idx + ": " + ByteBufUtil.hexDump(in));
        }
    }
    if (in.readableBytes() == 0)
        this.idx = 0;
    else
        this.idx = idx;
}

From source file:com.jamierf.jsonrpc.util.JsonObjectDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (state == ST_CORRUPTED) {
        in.skipBytes(in.readableBytes());
        return;//from ww  w.j  av  a 2  s. c  o  m
    }

    // index of next byte to process.
    int idx = this.idx;
    int wrtIdx = in.writerIndex();

    if (wrtIdx > maxObjectLength) {
        // buffer size exceeded maxObjectLength; discarding the complete buffer.
        in.skipBytes(in.readableBytes());
        reset();
        throw new TooLongFrameException(
                "object length exceeds " + maxObjectLength + ": " + wrtIdx + " bytes discarded");
    }

    for (/* use current idx */; idx < wrtIdx; idx++) {
        byte c = in.getByte(idx);
        if (state == ST_DECODING_NORMAL) {
            decodeByte(c, in, idx);

            // All opening braces/brackets have been closed. That's enough to conclude
            // that the JSON object/array is complete.
            if (openBraces == 0) {
                ByteBuf json = extractObject(ctx, in, in.readerIndex(), idx + 1 - in.readerIndex());
                if (json != null) {
                    out.add(json);
                }

                // The JSON object/array was extracted => discard the bytes from
                // the input buffer.
                in.readerIndex(idx + 1);
                // Reset the object state to get ready for the next JSON object/text
                // coming along the byte stream.
                reset();
            }
        } else if (state == ST_DECODING_ARRAY_STREAM) {
            decodeByte(c, in, idx);

            if (!insideString && (openBraces == 1 && c == ',' || openBraces == 0 && c == ']')) {
                // skip leading spaces. No range check is needed and the loop will terminate
                // because the byte at position idx is not a whitespace.
                for (int i = in.readerIndex(); Character.isWhitespace(in.getByte(i)); i++) {
                    in.skipBytes(1);
                }

                // skip trailing spaces.
                int idxNoSpaces = idx - 1;
                while (idxNoSpaces >= in.readerIndex() && Character.isWhitespace(in.getByte(idxNoSpaces))) {
                    idxNoSpaces--;
                }

                ByteBuf json = extractObject(ctx, in, in.readerIndex(), idxNoSpaces + 1 - in.readerIndex());
                if (json != null) {
                    out.add(json);
                }

                in.readerIndex(idx + 1);

                if (c == ']') {
                    reset();
                }
            }
            // JSON object/array detected. Accumulate bytes until all braces/brackets are closed.
        } else if (c == '{' || c == '[') {
            initDecoding(c);

            if (state == ST_DECODING_ARRAY_STREAM) {
                // Discard the array bracket
                in.skipBytes(1);
            }
            // Discard leading spaces in front of a JSON object/array.
        } else if (Character.isWhitespace(c)) {
            in.skipBytes(1);
        } else {
            state = ST_CORRUPTED;
            throw new CorruptedFrameException(
                    "invalid JSON received at byte position " + idx + ": " + ByteBufUtil.hexDump(in));
        }
    }

    if (in.readableBytes() == 0) {
        this.idx = 0;
    } else {
        this.idx = idx;
    }
}

From source file:com.linecorp.armeria.client.endpoint.dns.DnsEndpointGroup.java

License:Apache License

/**
 * Logs a warning message about an invalid record.
 *///from  w  ww .  j a v  a 2 s  .  co m
final void warnInvalidRecord(DnsRecordType type, ByteBuf content) {
    if (logger().isWarnEnabled()) {
        final String dump = ByteBufUtil.hexDump(content);
        logger().warn("{} Skipping invalid {} record: {}", logPrefix(), type.name(),
                dump.isEmpty() ? "<empty>" : dump);
    }
}