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:at.yawk.dbus.protocol.object.StringObject.java

static StringObject deserialize(AlignableByteBuf buf) {
    buf.alignRead(4);//from w w  w . ja va2s.c om
    int len = Math.toIntExact(buf.readUnsignedInt());
    ByteBuf bts = buf.readBytes(len);
    if (buf.readByte() != 0) {
        throw new DeserializerException("String not properly NUL-terminated");
    }
    return new StringObject(bts.toString(StandardCharsets.UTF_8));
}

From source file:books.netty.protocol.http.xml.codec.AbstractHttpXmlDecoder.java

License:Apache License

protected Object decode0(ChannelHandlerContext arg0, ByteBuf body) throws Exception {
    factory = BindingDirectory.getFactory(clazz);
    String content = body.toString(UTF_8);
    if (isPrint)/*from   w ww .  ja  v a2 s .  c  o  m*/
        System.out.println("The body is : " + content);
    reader = new StringReader(content);
    IUnmarshallingContext uctx = factory.createUnmarshallingContext();
    Object result = uctx.unmarshalDocument(reader);
    reader.close();
    reader = null;
    return result;
}

From source file:bzh.ygu.fun.chitchat.HttpChitChatServerHandler.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);//from   w w w  .  j ava 2  s. c  o m
        }
        String uri = request.uri();
        HttpMethod method = request.method();
        Root root = Root.getInstance();
        buf.setLength(0);
        contentBuf.setLength(0);

        if (method == HttpMethod.POST) {
            if (uri.equals("/chitchat")) {

                currentAction = "Add";
            }
        }
        if (method == HttpMethod.GET) {
            if (uri.startsWith(LATEST)) {
                latestFromWho = decode(uri.substring(LATEST_SIZE));
                currentAction = "Latest";
                Message m = root.getLatest(latestFromWho);
                if (m != null) {
                    //{"author":"Iron Man", "text":"We have a Hulk !", "thread":3,"createdAt":1404736639715}
                    buf.append(m.toJSON());
                }
            }
            if (uri.startsWith(THREADCALL)) {
                currentAction = "Thread";
                String threadId = uri.substring(THREADCALL_SIZE);
                MessageThread mt = root.getMessageThread(threadId);
                if (mt != null) {
                    //{"author":"Iron Man", "text":"We have a Hulk !", "thread":3,"createdAt":1404736639715}
                    buf.append(mt.toJSON());
                }

            }
            if (uri.startsWith(SEARCH)) {
                String stringToSearch = decode(uri.substring(SEARCH_SIZE));
                currentAction = "search";
                List<Message> lm = root.search(stringToSearch);
                //[{"author":"Loki", "text":"I have an army !", "thread":3,
                //"createdAt":1404736639710}, {"author":"Iron Man", "text":"We have a Hulk !",
                //   "thread":3, "createdAt":1404736639715}]
                buf.append("[");
                if (!lm.isEmpty()) {
                    Iterator<Message> it = lm.iterator();
                    Message m = it.next();
                    buf.append(m.toJSON());
                    while (it.hasNext()) {
                        m = it.next();
                        buf.append(", ");
                        buf.append(m.toJSON());
                    }
                }

                buf.append("]");
            }
        }
    }

    if (msg instanceof HttpContent) {
        Root root = Root.getInstance();
        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            contentBuf.append(content.toString(CharsetUtil.UTF_8));
        }

        if (msg instanceof LastHttpContent) {
            //                buf.append("END OF CONTENT\r\n");
            if (currentAction.equals("Add")) {
                addMessageFromContent(contentBuf.toString(), root);
                currentAction = "None";
            }
            LastHttpContent trailer = (LastHttpContent) msg;

            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:ch07.handlers.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  a  v  a 2 s .c  om*/
        }

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

        buf.append("VERSION: ").append(request.protocolVersion()).append("\r\n");
        buf.append("HOSTNAME: ").append(HttpHeaders.getHost(request, "unknown")).append("\r\n");
        buf.append("REQUEST_URI: ").append(request.uri()).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.uri());
        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:cloudfoundry.norouter.f5.dropsonde.LineEventDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext context, ByteBuf buffer, List<Object> out) throws Exception {
    buffer.markReaderIndex();/*from   w w w .j a  v a2  s. c  o m*/
    try {
        final String command = nextString(buffer);
        // Extract event type
        switch (command) {
        case "LOG":
            decodeLogEvent(context, buffer, out);
            break;
        default:
            throw new IllegalStateException("Unknown command " + command);
        }
    } catch (Exception e) {
        buffer.resetReaderIndex();
        throw new DecoderException("Invalid line event: " + buffer.toString(StandardCharsets.UTF_8), e);
    }
}

From source file:cloudfoundry.norouter.f5.dropsonde.LineEventDecoder.java

License:Open Source License

private void decodeLogEvent(ChannelHandlerContext context, ByteBuf buffer, List<Object> out) {
    final String ltmIdentifier = nextString(buffer);
    final String address = nextString(buffer);
    final String timestamp = nextString(buffer);
    final String requestId = nextString(buffer);
    final String message = buffer.toString(StandardCharsets.UTF_8);
    out.add(new LogEvent(ltmIdentifier, NorouterUtil.toSocketAddress(address),
            Instant.ofEpochMilli(Long.valueOf(timestamp)), UUID.fromString(requestId), message));
}

From source file:cn.dennishucd.nettyhttpserver.HttpServerHandler.java

License:Apache License

@SuppressWarnings("deprecation")
@Override// ww  w. j a  v a2s  .  c om
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        request = (HttpRequest) msg;

        if (HttpUtil.is100ContinueExpected(request)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }

        if (!request.uri().equalsIgnoreCase(URL)) {
            sendError(ctx, NOT_FOUND);

            return;
        }
    }

    if (msg instanceof HttpContent) {
        HttpContent content = (HttpContent) msg;
        ByteBuf buf = content.content();
        UserToken ut = CTools.JSONStr2Object(buf.toString(io.netty.util.CharsetUtil.UTF_8), UserToken.class);

        logger.info("request body: " + buf.toString(io.netty.util.CharsetUtil.UTF_8));
        buf.release();

        boolean keepAlive = HttpUtil.isKeepAlive(request);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK,
                Unpooled.wrappedBuffer(CONTENT.getBytes()));
        response.headers().set(CONTENT_TYPE, "application/json");
        response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());

        logger.info("response body: " + CONTENT);

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, KEEP_ALIVE);
            ctx.write(response);
        }

    } else {
        ctx.fireChannelRead(msg);
    }
}

From source file:cn.wantedonline.puppy.httpserver.component.HttpResponse.java

License:Apache License

public String getContentString() {
    if (StringTools.isEmpty(contentString)) {
        ByteBuf buf = this.content();
        if (AssertUtil.isNull(buf)) {
            return null;
        }//from w  w  w.  ja  va 2s  .  c  o m
        return buf.toString(contentCharset);
    }
    return contentString;
}

From source file:com.agrn.senqm.network.connection.ConnectionHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext context, Object messageReceived) {
    ByteBuf buffer = (ByteBuf) messageReceived;
    String bufferContent = buffer.toString(Charset.defaultCharset());

    connection.messageReceived(jsonToMessage(bufferContent));
}

From source file:com.bala.learning.learning.netty.HttpServerHandler.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);//from www.j  a va  2 s  . c om
        }

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