Example usage for io.netty.buffer ByteBuf toString

List of usage examples for io.netty.buffer ByteBuf toString

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf toString.

Prototype

public abstract String toString(Charset charset);

Source Link

Document

Decodes this buffer's readable bytes into a string with the specified character set name.

Usage

From source file:com.streamsets.pipeline.lib.parser.udp.syslog.SyslogParser.java

License:Apache License

@Override
public List<Record> parse(ByteBuf buf, InetSocketAddress recipient, InetSocketAddress sender)
        throws OnRecordErrorException {
    List<Record> records = new LinkedList<>();
    List<SyslogMessage> messages = new LinkedList<>();
    try {// w  ww.j  av a 2 s  .co m
        new SyslogDecoder(charset).decodeStandaloneBuffer(buf, messages, sender, recipient);
        for (SyslogMessage message : messages) {
            records.add(buildRecord(message));
        }
        return records;
    } catch (OnRecordErrorException e) {
        // throw new exception with record populated with raw message
        Record record = context.createRecord(generateRecordId(sender));
        record.set(Field.create(buf.toString(charset)));
        throw new OnRecordErrorException(record, e.getErrorCode(), e.getParams());
    }
}

From source file:com.tesora.dve.db.mysql.portal.protocol.MSPComInitDBRequestMessage.java

License:Open Source License

@Override
protected String unmarshall(ByteBuf source) {
    if (decodingCharset == null)
        throw new IllegalStateException(
                "initDB request cannot unmarshall a packet without a decoding charset.");
    source.skipBytes(1);//skip type field.
    return source.toString(decodingCharset);
}

From source file:com.tesora.dve.db.mysql.portal.protocol.MSPComPrepareStmtRequestMessage.java

License:Open Source License

@Override
protected String unmarshall(ByteBuf source) {
    source.skipBytes(1);//skip type field.
    return source.toString(decodingCharset);
}

From source file:com.tesora.dve.mysqlapi.repl.messages.MyRotateLogEvent.java

License:Open Source License

@Override
public void unmarshallMessage(ByteBuf cb) {
    position = cb.readLong();/*  w  w  w. j a v  a  2  s. c  o  m*/
    newLogFileName = cb.toString(CharsetUtil.UTF_8);
    cb.skipBytes(cb.readableBytes());//consume the rest of the buffer.
}

From source file:com.test.zp.netty.EchoClientHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    System.out.println("channel read");
    ctx.write(msg);/*from   w w  w. ja  va2  s . c  om*/

    ByteBuf in = (ByteBuf) msg;
    System.out.println(in.toString(io.netty.util.CharsetUtil.US_ASCII));

}

From source file:com.topsec.bdc.platform.api.server.http.HttpSnoopServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {

    if (msg instanceof HttpRequest) {
        //?HTTP?/*from  w  ww .  j  a  va2 s .co  m*/
        //HttpRequest request = this._request = (HttpRequest) msg;
        this._request = (HttpRequest) msg;
        //
        _requestBodyBuf.setLength(0);
        /*
        System.out.println("===================================\r\n");
                
        System.out.println("VERSION: " + request.getProtocolVersion());
        System.out.println("HOSTNAME: " + HttpHeaders.getHost(request, "unknown"));
        System.out.println("REQUEST_URI: " + request.getUri());
                
        HttpHeaders headers = request.headers();
        if (!headers.isEmpty()) {
        for (Map.Entry<String, String> h : headers) {
            String key = h.getKey();
            String value = h.getValue();
            System.out.println("HEADER: " + key + " = " + value);
        }
        }
                
        Map<String, List<String>> params = queryStringDecoder.parameters();
        if (!params.isEmpty()) {
        for (Entry<String, List<String>> p : params.entrySet()) {
            String key = p.getKey();
            List<String> vals = p.getValue();
            for (String val : vals) {
                System.out.println("PARAM: " + key + " = " + val);
            }
        }
        }
        //
        System.out.println("===================================");
        */

    }

    if (msg instanceof HttpContent) {
        //?HTTP BODY BODY?chunked?CHUNKED????
        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            _requestBodyBuf.append(content.toString(CharsetUtil.UTF_8));
            //content.release();
        }
        //??Response??
        if (msg instanceof LastHttpContent) {
            //
            LastHttpContent trailer = (LastHttpContent) msg;
            //
            String responseContent = null;
            //
            //fill response
            if (trailer.getDecoderResult().isSuccess() == false) {
                _responseStatus = HttpResponseStatus.BAD_REQUEST;
                responseContent = HttpResponseStatus.BAD_REQUEST.reasonPhrase();
            } else {
                try {
                    _responseStatus = HttpResponseStatus.OK;
                    responseContent = fireListenerSucceed(_requestBodyBuf.toString());
                } catch (Throwable e) {
                    e.printStackTrace();
                    _responseStatus = HttpResponseStatus.SERVICE_UNAVAILABLE;
                    responseContent = e.toString();
                }
            }

            try {
                //send back response and close connection
                writeResponseAndClose(ctx, responseContent);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                _requestBodyBuf.setLength(0);
            }
        }
    }
}

From source file:com.topsec.bdc.platform.api.test.http.snoop.HttpSnoopServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {

    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;

        if (HttpHeaders.is100ContinueExpected(request)) {
            send100Continue(ctx);//  w ww .  j ava  2  s .  co m
        }

        buf.setLength(0);
        buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        buf.append("===================================\r\n");

        buf.append("VERSION: ").append(request.getProtocolVersion()).append("\r\n");
        buf.append("HOSTNAME: ").append(HttpHeaders.getHost(request, "unknown")).append("\r\n");
        buf.append("REQUEST_URI: ").append(request.getUri()).append("\r\n\r\n");

        HttpHeaders headers = request.headers();
        if (!headers.isEmpty()) {
            for (Map.Entry<String, String> h : headers) {
                String key = h.getKey();
                String value = h.getValue();
                buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n");
            }
            buf.append("\r\n");
        }

        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());
        Map<String, List<String>> params = queryStringDecoder.parameters();
        if (!params.isEmpty()) {
            for (Entry<String, List<String>> p : params.entrySet()) {
                String key = p.getKey();
                List<String> vals = p.getValue();
                for (String val : vals) {
                    buf.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n");
                }
            }
            buf.append("\r\n");
        }

        appendDecoderResult(buf, request);
    }

    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            buf.append("CONTENT: ");
            buf.append(content.toString(CharsetUtil.UTF_8));
            buf.append("\r\n");
            appendDecoderResult(buf, request);
        }

        if (msg instanceof LastHttpContent) {
            buf.append("END OF CONTENT\r\n");

            LastHttpContent trailer = (LastHttpContent) msg;
            if (!trailer.trailingHeaders().isEmpty()) {
                buf.append("\r\n");
                for (String name : trailer.trailingHeaders().names()) {
                    for (String value : trailer.trailingHeaders().getAll(name)) {
                        buf.append("TRAILING HEADER: ");
                        buf.append(name).append(" = ").append(value).append("\r\n");
                    }
                }
                buf.append("\r\n");
            }

            if (!writeResponse(trailer, ctx)) {
                // If keep-alive is off, close the connection once the content is fully written.
                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
            }
        }
    }
}

From source file:com.train.client.test.NettyHttpClientTest.java

License:Apache License

private void print(NettyHttpResponse response) {
    System.out.println("STATUS: " + response.getStatus());
    System.out.println("VERSION: " + response.getVersion());
    System.out.println();//from   w  w w.j a  va  2s .  c  o  m

    if (!response.getHeaders().isEmpty()) {
        for (String name : response.getHeaders().names()) {
            for (String value : response.getHeaders().getAll(name)) {
                System.out.println("HEADER: " + name + " = " + value);
            }
        }
    }
    System.out.println("CHUNKED CONTENT :");
    for (ByteBuf buf : response.getContents()) {
        System.out.print(buf.toString(CharsetUtil.UTF_8));
    }
}

From source file:com.turo.pushy.apns.ApnsClientHandler.java

License:Open Source License

@Override
public int onDataRead(final ChannelHandlerContext context, final int streamId, final ByteBuf data,
        final int padding, final boolean endOfStream) {
    log.trace("Received data from APNs gateway on stream {}: {}", streamId,
            data.toString(StandardCharsets.UTF_8));

    final int bytesProcessed = data.readableBytes() + padding;

    if (endOfStream) {
        final Http2Stream stream = this.connection().stream(streamId);
        this.handleEndOfStream(context, this.connection().stream(streamId),
                (Http2Headers) stream.getProperty(this.responseHeadersPropertyKey), data);
    } else {//from  ww  w . jav  a  2  s  . c  om
        log.error("Gateway sent a DATA frame that was not the end of a stream.");
    }

    return bytesProcessed;
}

From source file:com.turo.pushy.apns.ApnsClientHandler.java

License:Open Source License

private void handleEndOfStream(final ChannelHandlerContext context, final Http2Stream stream,
        final Http2Headers headers, final ByteBuf data) {

    final PushNotificationPromise<ApnsPushNotification, PushNotificationResponse<ApnsPushNotification>> responsePromise = stream
            .getProperty(this.responsePromisePropertyKey);

    final ApnsPushNotification pushNotification = responsePromise.getPushNotification();

    final HttpResponseStatus status = HttpResponseStatus.parseLine(headers.status());

    if (HttpResponseStatus.OK.equals(status)) {
        responsePromise.trySuccess(new SimplePushNotificationResponse<>(responsePromise.getPushNotification(),
                true, getApnsIdFromHeaders(headers), null, null));
    } else {/*  w w  w  . java 2s  .  co m*/
        if (data != null) {
            final ErrorResponse errorResponse = GSON.fromJson(data.toString(StandardCharsets.UTF_8),
                    ErrorResponse.class);
            this.handleErrorResponse(context, stream.id(), headers, pushNotification, errorResponse);
        } else {
            log.warn("Gateway sent an end-of-stream HEADERS frame for an unsuccessful notification.");
        }
    }
}